Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 219

PROGRAMMING IN C Bsc I YR/I-SEM

Bachelor Of Science
PROGRAMMING IN C
I-Year I-Sem Syllbus
4:credits Internal-20M+External-80M
_________________________________________________________________________
Unit –I
Computer Fundamentals: Introduction of Computers, Classification of Computers,
Anatomy of a Computer, Memory Hierarchy, Introduction to OS, Operational
Overview of a CPU.Program Fundamentals: Generation and Classification of
Programming Languages, Compiling, Interpreting, Loading, Linking of a Program,
Developing Program, SoftwareDevelopment.
Algorithms: Definitions, Different Ways of Stating Algorithms(Step-form, Pseudo-
code, Flowchart), Strategy for Designing Algorithms, Structured Programming
Concept.
Basics of C: Overview of C, Developing Programs in C, Parts of Simple C Program,
Structure of a C Program, Comments, Program Statements, C Tokens, Keywords,
Identifiers, Data Types, Variables, Constants, Operators and Expressions, Expression
Evaluation–precedence and associativity, Type Conversions.

Unit –II
Input-Output: Non-formatted and Formatted Input and Output Functions, Escape
Sequences,Control Statements: Selection Statements –if, if-else, nested if, nested if-
else, comma operator, conditional operator, switch; Iterative Statements–while, for,
do-while; Special Control Statement–goto, break, continue, return, exit.
Arrays and Strings:One-dimensional Arrays, Character Arrays, Functions from
ctype.h, string.h, Multidimensional Arrays.

Unit –III
Functions: Concept of Function, Using Functions, Call-by-Value VsCall-by-reference,
Passing Arrays to Functions, Score of Variables, Storage Classes, Inline Functions,
and Recursion.
Pointers: Introduction, Address of Operator (&),Pointer, Uses of Pointers, Arrays and
Pointers, Pointers and Strings, Pointers to Pointers, Array of Pointers, Pointer to
Array, Dynamic Memory Allocation.

Unit –IV
User-defined Data Types: Declaring a Structure (Union) and its members,
Initialization Structure (Union), Accessing members of a Structure (Union), Array of
Structures (Union),Structures versesUnions, Enumeration Types.
Files: Introduction, Using Files in C, Working with Text Files, Working with Binary
Files, Files of Records, Random Access to Files of Records, Other File Management
Functions

SIVA SIVNI DEGREE COLLEGE 1|Page


PROGRAMMING IN C Bsc I YR/I-SEM
UNIT-1
FUNDMENTALS OF COMPUTER
DEFINE COMPUTER:
Computer is derived from the Latin word ‘Compute’ which means to ‘calculate’. So
according to this definition, computer is a machine which can perform calculations
at very high speed.
• Basically, computer is defined as programmable machine which computes.
• Computer can be defined as a digital and automatic machine which takes input
from the user, process it, stores it if necessary and gives output in the desired form.
• A computer is an electronic device used to process data, converting the data into
information that is useful to the people.
• Computer is an electronic machine that can accept data: process it according to a
set of predefined instructions and then gives the results.
The main characteristics of a computer are:
• It responds to a specific set of instructions in a well-defined manner(algorithum
and Pseudocode).
• It can execute a prerecorded list of instructions (called program).
Computer is an advanced electronic device that takes raw data as an input from the
user and processes it under the control of a set of instructions (called program),
produces a result (output), and saves(memory) it for future use.
Charles Babbage is considered to be the father of modern digital computers
He designed “Difference Engine” in 1822.
He designed a fully automatic analytical engine in 1842 for performing basic
arithmetic functions. His efforts established a number of principles that are
fundamental to the design of any digital computer.
ABBREVIATION OF COMPUTER:
C-Common
O-Operated/ Oriented
M-Machine
P-Purposively
U-Used for
T-Technical and
E=Educational and Electronically
R-Research
S-System
Or
A computer is a data processor. It can accept input, which may be either data or
instructions or both.

SIVA SIVNI DEGREE COLLEGE 2|Page


PROGRAMMING IN C Bsc I YR/I-SEM
Functionalities Of A Computer
All types of computers follow the same basic logical structure and perform the
following five basic Operations for converting raw input data into information
useful to their users.
Takes Input
The process of entering data and instructions into the computer system.
Stores Data
Saving data and instructions so that they are available for processing as and when
required.
Processing the Data
Performing arithmetic, and logical operations on data in order to convert them into
useful information.
Output the Information
The process of producing useful information or results for the user, such as a
printed report or visual display.
Control the workflow
Directs the manner and sequence in which all of the above operations are
performed.
Basic Components Of Computer
Input Unit
This unit contains devices with the help of which we enter data into the computer.
This unit creates a link between the user and the computer. The input devices
translate the information into a form understandable by the computer.
CPU (Central Processing Unit)
CPU is considered as the brain of the computer. CPU performs all types of data
processing operations. It stores data, intermediate results, and instructions
(program). It controls the operation of all parts of the computer.
CPU itself has the following three components −
ALU (Arithmetic Logic Unit) *Memory Unit *Control Unit
Memory Unit : Memory unit stores the data, instructions, intermediate results and
output,temporarily, during the processing of data.
Output Unit
The output unit consists of devices with the help of which we get the information
from the computer. This unit is a link between the computer and the users. Output
devices translate the computer's output into a form understandable by the users.
The Anatomy Of A Computer
A computer can accept input, process or store data, and produce output according to
a set of instructions which are fed into it.
A computer system can be divided into two components which are responsible for
providing the mechanisms to input and output data, to manipulate and process data,
and to electronically control the various input/output, and their storage.
They are known as hardware and software.
The hardware is the tangible parts of the computer. Whereas, the software is the
intangible set of instructions that control the hardware and make it perform specific
tasks. Without software, a computer is effectively useless.

Hardware
Hardware is the physical components of a computer that includes all mechanical,
electrical, electronic and magnetic parts attached to it. Ex: CPU, Monitor, Keyboard,
Mouse, Printer, Speakers… etc.

SIVA SIVNI DEGREE COLLEGE 3|Page


PROGRAMMING IN C Bsc I YR/I-SEM
A computer consists of the following Major hardware components:
*Input and output devices
*Central processing unit (CPU)
*Memory unit and storage devices
*Interface unit
SOFTWARE
Software is a generic term for organized collection of computer data and instructions.
It is responsible for controlling, integrating, and managing the hardware components
of a computer and to accomplish specific tasks. In other words, software tells the
computer what to do and how to do it.
 System software
 Application software
 Utility software
THE ANATOMY OF A DESKTOP COMPUTER
A desktop computer is a computer that fits on or under a desk. They utilize
peripheral devices for interaction, such as a keyboard and mouse for input, and
display devices like a monitor, projector, or television.

WRITE ABOUT PARTS OF A PC


1. A keyboard with 26 English letters, 10 digits, several special characters such as +,
-, (, etc., and some extra keys called control keys and 12 function keys. This is used to
enter program and data for storage in the computer's memory. It is called an input
unit.
2. A Video Display Unit (also called a monitor) is similar to a TV screen. The screen
size is normally 15" (diagonal). It is normally a color screen and is used to display
text, images and video.
It is also used to display small graphics symbols called icons that assist you to give
commands to the computer. This is called a Graphical User Interface (GUI). The VDU
is the most common output unit of a computer.
3. Mouse: To effectively give commands using GUI, every PC has a small hand-held
unit called a mouse which normally has two buttons that can be pressed (called
clicking). The mouse is moved on a rubber pad. As the mouse is moved, a small
picture of an arrow moves on the display screen.

SIVA SIVNI DEGREE COLLEGE 4|Page


PROGRAMMING IN C Bsc I YR/I-SEM
The arrow can be placed over a graphical icon and the mouse button clicked twice in
quick succession to initiate an action by the computer. The mouse is also an input
unit as it is used to initiate commands to a computer.
4. Processor (CPU): A separate box is used in most recent desktop PCs to
accommodate the CPU, the main memory, the secondary storage and the power
supply. This box also has a number of sockets called ports to connect external devices
such as a printer, loudspeaker, flash memory (popularly known as pen drive),
microphone, etc., and also to connect a communication system such as a local area
network or the Internet.
5. Motherboard the CPU is a microprocessor mounted on what is known as a
motherboard. Besides the microprocessor, the motherboard also accommodates
electronic circuits to interface the microprocessor with several other units such as a
network interface card (NIC), sound card and graphics card. The main memory is
also mounted on the motherboard.
6. Memory: PCs have very large main memory with capacity to store any type of
data.
The secondary storage consists of a large hard disk that is in a sealed unit and is
connected to the main memory (with circuits inside the box), a DVD-RW, and a
CDROM.
7. A disk is used to store several programs required to use the computer. In modern
PCs a disk can store several hundred billion characters (specified as 500 GB). The disk
store is essential for the functioning of a PC.
8. A pen drive or flash memory is pushed into a slot called a USB port and is used to
store smaller files and is a removable store. Another removable store is CDROM
(similar to audio CD) which has a capacity of around half a billion characters (500
MB). Besides CDROM must PCs also have a DVD-RW (Digital Versatile Disk-
Recordable and rewritable) with capacities ranging from 4.7 GB to 17 GB.
9.Most PCs today are called Multimedia PCs as they are capable of acquiring and
processing pictures, audio, and video data besides text and numbers. In order to
acquire and process multimedia data, PCs are equipped with:
(i) A box called a scanner external to the PC and connected to it by a connecting cable.
The scanner is used to convert text or pictures placed on it to digital form for storage
in the memory of the computer.
(ii) A printer that can print pictures besides text and numbers.
(iii) A microphone and an audio jack to accept audio data.
(iv) An electronic circuit called a sound card which is connected to the CPU
motherboard to provide audio output.
(v) A pair of speakers to provide audio output obtained from the sound card of a PC.
(vi) An electronic circuit called a graphics card to display pictures and video. This
card is mounted on the motherboard.
(vii) A small electronic video camera external to the PC to capture images and video.

SIVA SIVNI DEGREE COLLEGE 5|Page


PROGRAMMING IN C Bsc I YR/I-SEM

What Are The Characteristics Of Computer


(Advantages of Computers)
Following are certain advantages of computers.
High Speed
Computer is a very fast device.
It is capable of performing calculation of very large amount of data.
The computer has units of speed in microsecond, nanosecond, and even the
picosecond.
It can perform millions of calculations in a few seconds as compared to man who will
spend many months to perform the same task.
Accuracy
In addition to being very fast, computers are very accurate.
The calculations are 100% error free.
Computers perform all jobs with 100% accuracy provided that the input is correct.
Storage Capability
Memory is a very important characteristic of computers.
A computer has much more storage capacity than human beings.
It can store large amount of data.
It can store any type of data such as images, videos, text, audio, etc.
Diligence : Unlike human beings, a computer is free from monotony, tiredness, and
lack ofconcentration.
It can work continuously without any error and boredom.
It can perform repeated tasks with the same speed and accuracy.
Versatility
A computer is a very versatile machine.
A computer is very flexible in performing the jobs to be done.
This machine can be used to solve the problems related to various fields.
At one instance, it may be solving a complex scientific problem and the verynext
moment it may be playing a card game.
Reliability
A computer is a reliable machine.
Modern electronic components have long lives.
Computers are designed to make maintenance easy.

SIVA SIVNI DEGREE COLLEGE 6|Page


PROGRAMMING IN C Bsc I YR/I-SEM
Automation
Computer is an automatic machine.
Automation is the ability to perform a given task automatically. Once the computer
receives a program i.e., the program is stored in the computer memory, then the
program and instruction can control the program execution without human
interaction.
Reduction in Paper Work and Cost
The use of computers for data processing in an organization leads to reduction in
paper work and results in speeding up the process.
As data in electronic files can be retrieved as and when required, the problem of
maintenance of large number of paper files gets reduced.
Though the initial investment for installing a computer is high, it substantially
reduces the cost of each of its transaction.
Disadvantages of Computers
No I.Q.
A computer is a machine that has no intelligence to perform any task.
Each instruction has to be given to the computer.
A computer cannot take any decision on its own.
Dependency
It functions as per the user’s instruction, thus it is fully dependent on humans.
Environment
The operating environment of the computer should be dust free and suitable.
No Feeling
Computers have no feelings or emotions.
It cannot make judgment based on feeling, taste, experience, and knowledge unlike
humans.
judgment based on feeling, taste, experience, and knowledge unlike humans.
List Out Applications Of Computers

*Business
A computer has high speed of calculation, diligence,
accuracy, reliability, or versatility which has made it
an integrated part in all business organizations.
Computer is used in business organizations for −
• Payroll calculations
• Budgeting
• Sales analysis
• Financial forecasting
• Managing employee database
• Maintenance of stocks, etc.
*Banking
Today, banking is almost totally dependent on computers.
Banks provide the following facilities −
• Online accounting facility, which includes checking current balance, making
deposits and overdrafts, checking interest charges, shares, and trustee records.
• ATM machines which are completely automated are making it even easier for
customers to deal with banks.
*Insurance
Insurance companies are keeping all records up-to-date with the help of computers.
Insurance companies,

SIVA SIVNI DEGREE COLLEGE 7|Page


PROGRAMMING IN C Bsc I YR/I-SEM
Finance houses, and stock broking firms are widely using computers for their
concerns.
Insurance companies are maintaining a database of all clients with information
showing −
• Procedure to continue with policies
• Starting date of the policies
• Next due installment of a policy *Maturity date * Interests due * Survival benefits
• Bonus
*Education
The computer helps in providing a lot of facilities in the education system.
• The computer provides a tool in the education system known as CBE.
• CBE involves control, delivery, and evaluation of learning.
• Computer education is rapidly increasing the graph of number of computer
students.
• There are a number of methods in which educational institutions can use a
computer to educate the students.
• It is used to prepare a database about performance of a student and analysis is
carried out on this basis.
*Marketing
In marketing, uses of the computer are following −
• Advertising − With computers, advertising professionals create art and graphics,
write and revise copy, and print and disseminate ads with the goal of selling more
products.
• Home Shopping − Home shopping has been made possible through the use of
computerized catalogues that provide access to product information and permit
direct entry of orders to be filled by the customers.
*Healthcare
Computers have become an important part in hospitals, labs, and dispensaries. They
are being used in hospitals to keep the record of patients and medicines. It is also
used in scanning and diagnosing different diseases. ECG, EEG, ultrasounds and CT
scans, etc. are also done by computerized machines.
Following are some major fields of health care in which computers are used.
• Diagnostic System − Computers are used to collect data and identify the cause of
illness.
• Lab-diagnostic System − All tests can be done and the reports are prepared by
computer.
• Patient Monitoring System − these are used to check the patient's signs for
abnormality such as in Cardiac Arrest, ECG, etc.
• Pharmacy Information System − Computer is used to check drug labels, expiry
dates, harmful side effects, etc.
• Surgery − Nowadays, computers are also used in performing surgery.
*Engineering Design
Computers are widely used for engineering purpose.
One of the major areas is CAD that provides creation and modification of images.
Some of the fields are −
*Computer Aided Design
• Structural Engineering − requires stress and strain analysis for design of ships,
buildings, budgets, airplanes, etc.
• Industrial Engineering − Computers deal with design, implementation, and
improvement of integrated systems of people, materials, and equipment.

SIVA SIVNI DEGREE COLLEGE 8|Page


PROGRAMMING IN C Bsc I YR/I-SEM
• Architectural Engineering − Computers help in planning towns, designing
buildings, determining a range of buildings on a site using both 2D and 3D drawings.
*Military
Computers are largely used in defense. Modern tanks, missiles, weapons, etc.
Military also employs computerized control systems. Some military areas where a
computer has been used are −
• Missile Control
• Military Communication
• Military Operation and Planning
• Smart Weapons
*Communication
Communication is a way to convey a message, an idea, a picture, or speech that is
received and understood clearly and correctly by the person for whom it is meant.
Some main areas in this category are
• E-mail *Chatting *Usenet *FTP *Telnet * Video-conferencing
*Government
Computers play an important role in government services. Some major fields in this
category
• Budgets
• Sales tax department
• Income tax department
• Computation of male/female ratio
• Computerization of voter’s lists
• Computerization of PAN card
* Weather Forecast: Computers are used to analyze and forecast the weather.
Classification Of Computers
EXPLAIN ABOUT DIGITAL AND ANALOG COMPUTERS
A digital computer uses distinct values to represent the data internally. All
information is represented using the digits Os and 1s. The computers that we use at
our homes and offices are digital computers.
Analog computer is another kind of a computer that represents data as variable
across a continuous range of values. The earliest computers were analog computers.
Analog computers are used for measuring of parameters that vary continuously in
real time, such as temperature, pressure and voltage. Analog computers may be more
flexible but generally less precise than digital computers
ANALOG COMPUTER DIGITAL COMPUTER
Analog computers works with Digital computers works with discrete
continuous values or these types of values or these types of systems process
systems process continuous data. discrete data.
Speed of analog computers is less Speed of digital computers is more than
than the digital computers. the analog computers.
Analog computer has very low or Digital computer has very big memory
limited memory and it can store it can store large amount of data.
fewer amounts of data.
Analog computer has no state. Digital computer has On and Off states
They are less reliable. They are more reliable.
Its performance is comparatively Its performance is very high. Its speed
low. Its speed of processing is not so of processing is very high.
high.

SIVA SIVNI DEGREE COLLEGE 9|Page


PROGRAMMING IN C Bsc I YR/I-SEM
An analog computer depends upon A digital computer does not depend
physical variations. upon physical variations.
It provides results with less It provides results with higher accuracy
accuracy as compared to digital as compared to analog computers.
computers.
They are difficult to use and have They are not so difficult to use. Digital
complex architecture. computers do not have so complex
architecture like analog computers.
Readability of analog computer is Readability of digital computer is high.
low.
Analog computers show the result Digital computers show the result in
in terms of voltage signals. computer display screen.
They employs analog encoding. They employs digital encoding.
Power consumption is high. They Power consumption is low. It can be
are usually special purpose devices. general purpose devices.
Examples includes analog clock and Examples includes Digital laptop,
thermometer etc. digital camera, digital watches etc.
WHAT ARE THE DIFFERENTTYPESOFCOMPUTERS

VARIOUS DIGITALCOMPUTERASPERTHEPURPOSE
General Purpose digital computers: These computers aretheoretically used for any type
of applications. These computers canbe used in solving a business Problem and also
used to solve mathematical equation with same accuracy and consistency.Most of the
computers now are general purpose digital computers.
Special Purpose Computers: These digital computers are designed,made and used for
any specific job. These are usually used for those purposes which are critical and need
great accuracy and response like Satellitelaunching weather forecasting etc.

SIVA SIVNI DEGREE COLLEGE 10 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
VARIOUS TYPES OF COMPUTER SYSTEMS BASED ON USAGE
Analog Computers
It is particularly designed to process analogue data. Continuous data that changes
continuously and cannot have discrete values is called analogue data. So, an analogue
computer is used where we don’t need exact values or need approximate values such
as speed, temperature, pressure etc. The analog computers operate by measuring
instead of counting.
The analog computer works on the supply of continuous electrical signals.
It can directly accept the data from the measuring device without first converting it
into numbers and codes. It measures the continuous changes in physical quantity.
It gives output as a reading on a dial or scale. For example speedometer, mercury
thermometer, etc.

Characteristics of analog computer


The analog computer has the following important characteristics:
 It operates by measuring.
 It requires physical analog.
 It functions on continuously varying quantities.
 The output is usually represented in the form of graph.
 In analog, the calculations are first converted in equation &later converted into
electrical signals.
 The accuracy of the output is poor.
 It has limited memory space.
 It is not versatile. i.e., it has limited application.
 The speed of analog computer is low.
 Not suitable for business and industry.
Digital Computers
These computers work with quantities represented as digits. They operate on discrete
quantities. In digital computer, both numeric and non-numeric information are
represented as strings of digits. The information is given to the computer in the form
of discrete electrical signals.
The basic operation performed by a digital computer is addition.
Digital computers are designed in such a way that it can easily perform calculations
and logical operations at high speed. It takes raw data as an input and processes it
with programs stored in its memory to produce the final output.
It only understands the binary input 0 and 1, so the raw input data is converted to 0
and 1 by the computer and then it is processed by the computer to produce the result
or final output. All modern computers, like laptops, desktops including smartphones
are digital computers.

SIVA SIVNI DEGREE COLLEGE 11 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Characteristics of digital computer
 The digital computer has the following characteristics:
 It operates by counting.
 It functions on discrete numbers.
 The calculations are converted into binary numbers i.e., 1s and 0s.
 The output is represented in the form of discrete values.
 Its accuracy is good.
Hybrid computers:
The computer which possesses the
features of both analog and digital
computers are called hybrid
computers.
 This computer accepts either
digital or analog or both types of
input and gives the results as per
requirements through special
devices.
 In the hybrid computers a
converter is fixed to convert the
analog data into digital data and
vice versa. These are special purpose devices and are not widely used.
 Hybrid computers are fast like an analog computer and have memory, and accuracy
like a digital computer. So, it has the ability to process both continuous and discrete
data.
 For working when it accepts analog signals as input then it converts them into
digital form before processing the input data. So, it is widely used in specialized
applications where both analog and digital data is required to be processed.
 A processor which is used in petrol pumps that converts the measurements of fuel
flow into quantity and price is an example of a hybrid computer.
TYPES COMPUTERS ACCORDING TO THE
OPERATION SIZE
Classification of digital computer as per size and
capabilities
1. Super Computers
2. Main frame Computer
3. Mini Computers
4. Micro Computers.
Computer Systems are classified as Microcomputers,
Minicomputers, Mainframes and Supercomputers.
1.Micro Computer
• Are the smallest computer systems on the basis of
size
• Are called microcomputer because microprocessor
is used as its CPU which are very small
• Are also called PC (Personal Computers) or home
computers
• Smallest are laptop, notebook and palmtop computers.
• Examples: IBM Pentium PC, Apple/Macintosh etc

SIVA SIVNI DEGREE COLLEGE 12 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Characteristics:
• Smallest in term of size
• Speed and cost is also less as compared with other super, mainframe and mini
computers.
• Since a single user system is used, storage devices and memory are smaller size.
Microcomputers are of two types: Personal Computers and Workstations
1.1 Personal Computers (PCs)
 It can be defined as a small, relatively inexpensive computer designed for an
individual user.
 In price, personal computers range anywhere from a few hundred pounds to over
five thousand pounds. All are based on the microprocessor technology that enables
manufacturers to put an entire CPU on one chip.
 PCs are used for word processing, accounting, desktop publishing, and for running
spreadsheet and database management applications. At home, the most popular use
for personal computers is for playing games and recently for surfing the Internet.
 Personal computers first appeared in the late 1970s. One of the first and most popular
personal computers was the Apple II, introduced in 1977 by Apple Computer.
During the late 1970s and early 1980s, new models and competing operating systems
seemed to appear daily.
1.2 Workstation
 It is a type of computer used for engineering applications, desktop publishing,
software development, and other types of applications that require a moderate
amount of computing power and relatively high-quality graphics capabilities.
 Workstations generally come with a large, high-resolution graphics screen, at large
amount of RAM, built-in network support, and a graphical user interface. The most
common operating systems for workstations are UNIX and Windows NT.
 Like personal computers, most workstations are single-user computers. However,
workstations are typically linked together to form a local-area network, although
they can also be used as stand-alone systems.
The most powerful workstations are called super micros.
N.B.: In networking, workstation refers to any computer connected to a local-area
network.
It could be a workstation or a personal computer.
1.3 Portable Computers
Computers are becoming smaller yet more powerful. Portable computer are gaining
rapid popularity and can be easily carried around. There are three categories of
portable computers viz. Laptops or Notebook PCs, Subnotebooks and Personal
Digital Assistants.

2. Minicomputers
 Are medium sized computers on the basis of size
 A centrally located server or CPU is connectedwith more than 50 terminals.
 Examples: Prime 9755, Vax 36 etc.

Characteristics:
 Medium size
SIVA SIVNI DEGREE COLLEGE 13 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 More than 50 terminals and large capacitystorage devices than microcomputers.
 Used for general purpose.
 Used in medium sized organizations and corporation for their database
administration.
3. Mainframe Computer
 Are the largest types of computers
 Are used in large organizationslike insurance companies, banks where people need
frequent access to the same data, which is usuallyorganized into one or more huge
databases.
 Examples: IBM 1401, ICL 2950/10, IBM S/390 etc
Characteristics:
 Very large in size.
 Central processor, central administration
 More than 100 terminals, large capacity storage devices used
 Fastest and more expensive system.
 Used by large agencies and government for large scale data processing.
4. SuperComputer
 Are the most sophisticated and powerful computers. They are large in size
 These systems are built to process t h e amount of data and the fastest
supercomputer canperform more than 1 trillion calculations per second.
 Some super computers are Cray T90, Super Cray, Cyber 205 and Super SXI.
 These can house thousands of processors
 These speed and power make supercomputers ideal for handling large and highly
complexproblems that require extreme calculating power.
 Used in weather forecasting, nuclear fusion, study of DNA structures.
 Can cost tens of millions of dollars and consume enough electricity to power dozen of
homes.
 They are often housed in protective rooms with special cooling systems, power
protection andother security features.
 Because of their size and cost, super computers are relatively rare, used only
by largecorporations, universities and government agencies that can afford them.
COMPUTER – GENERATIONS
Generation in computer terminology is a change in technology a computer is/was
being used. Initially, the generation term was used to distinguish between varying
hardware technologies. Nowadays, generation includes both hardware and
software, which together make up an entire computer system.
There are five computer generations known till date.
1First Generation: The period of first generation: 1946-1959. Vacuum tube based.
2Second Generation: The period of second generation: 1959-1965. Transistor based.
3Third Generation: The period of third generation: 1965-1971.
Integrated Circuit based.
4Fourth Generation: The period of fourth generation: 1971-1980.
VLSI microprocessor based.
5Fifth Generation:The period of fifth generation: 1980-onwards. ULSI
microprocessor based.

First Generation
The period of first generation was from 1946-1959. The computers of first generation
used vacuum tubes as the basic components for memory and circuitry for CPU
(Central Processing Unit). These tubes, like electric bulbs, produced a lot of heat and
SIVA SIVNI DEGREE COLLEGE 14 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
the installations used to fuse frequently. Therefore, they were very expensive and
only large organizations were able to afford it.
In this generation, mainly batch processing operating system was used. Punch cards,
paper tape, and magnetic tape was used as input and output devices. The computers
in this generation used machine code as the programming language.
The main features of the first generation are −
 Vacuum tube technology
 Unreliable
 Supported machine language only
 Very costly
 Generated a lot of heat
 Slow input and output devices
 Huge size
 Need of AC
 Non-portable
 Consumed a lot of electricity
Some computers of this generation were −
 ENIAC EDVAC UNIVAC IBM-701 IBM-650
Second Generation
The period of second generation was from 1959-1965. In this generation, transistors
were used that were cheaper, consumed less power, more compact in size, more
reliable and faster than the first generation machines made of vacuum tubes. In this
generation, magnetic cores were used as the primary memory and magnetic tape and
magnetic disks as secondary storage devices.
In this generation, assembly language and high-level programming languages like
FORTRAN, COBOL were used. The computers used batch processing and
multiprogramming operating system.
The main features of second generation are −
 Use of transistors
 Reliable in comparison to first generation computers
 Smaller size as compared to first generation computers
 Generated less heat as compared to first generation computers
 Consumed less electricity as compared to first generation computers
 Faster than first generation computers
 Still very costly
 AC required
 Supported machine and assembly languages
Some computers of this generation were −
 IBM 1620 IBM 7094 CDC 1604 CDC 3600 UNIVAC 1108
Third Generation
The period of third generation was from 1965-1971. The computers of third
generation used Integrated Circuits (ICs) in place of transistors. A single IC has many
transistors, resistors, and capacitors along with the associated circuitry.
The IC was invented by Jack Kilby. This development made computers smaller in
size, reliable, and efficient. In this generation remote processing, time-sharing,
multiprogramming operating system were used.
High-level languages (FORTRAN-II TO IV, COBOL, PASCAL PL/1, BASIC,
ALGOL-68 etc.) were used during this generation.
The main features of third generation are −
 IC used

SIVA SIVNI DEGREE COLLEGE 15 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 More reliable in comparison to previous two generations
 Smaller size
 Generated less heat
 Faster
 Lesser maintenance
 Costly
 AC required
 Consumed lesser electricity
 Supported high-level language
Some computers of this generation were −
 IBM-360 series
 Honeywell-6000 series
 PDP (Personal Data Processor)
 IBM-370/168
 TDC-316
Fourth Generation
The period of fourth generation was from 1971-1980. Computers of fourth generation
used Very Large Scale Integrated (VLSI) circuits. VLSI circuits having about 5000
transistors and other circuit elements with their associated circuits on a single chip
made it possible to have microcomputers of fourth generation.
Fourth generation computers became more powerful, compact, reliable, and
affordable. As a result, it gave rise to Personal Computer (PC) revolution. In this
generation, time sharing, real time networks, distributed operating system were
used. All the high-level languages like C, C++, DBASE etc., were used in this
generation.
The main features of fourth generation are −
 VLSI technology used
 Very cheap
 Portable and reliable
 Use of PCs
 Very small size
 Pipeline processing
 No AC required
 Concept of internet was introduced
 Great developments in the fields of networks
Some computers of this generation were −
 STAR 1000 PDP 11 CRAY-1(Super Computer) CRAY-X-MP(Super Computer)
Fifth Generation
The period of fifth generation is 1980-till date. In the fifth generation, VLSI technology
became ULSI (Ultra Large Scale Integration) technology, resulting in the production
of microprocessor chips having ten million electronic components.
This generation is based on parallel processing hardware and AI (Artificial
Intelligence) software. AI is an emerging branch in computer science, which
interprets the means and method of making computers think like human beings. All
the high-level languages like C and C++, Java, .Net etc., are used in this generation.

AI includes −
 Robotics
 Neural Networks
 Game Playing
SIVA SIVNI DEGREE COLLEGE 16 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 Development of expert systems to make decisions in real-life situations
 Natural language understanding and generation
The main features of fifth generation are −
 ULSI technology
 Development of true artificial intelligence
 Development of Natural language processing
 Advancement in Parallel Processing
 Advancement in Superconductor technology
 More user-friendly interfaces with multimedia features
 Availability of very powerful and compact computers at cheaper rates
Some computer types of this generation are −
 Desktop Laptop NoteBook UltraBook ChromeBook
DRAW A SIMPLE MODEL OF A COMPUTER (BLOCK DIAGRAM OF THE
COMPUTER)

Input Unit :This unit contains devices with the help of which we enter data into the
computer. This unit creates a link between the user and the computer. The input
devices translate the information into a form understandable by the computer.
CPU (Central Processing Unit) : CPU is considered as the brain of the computer. CPU
performs all types of data processing operations. It stores data, intermediate results,
and instructions (program). It controls the operation of all parts of the computer.
CPU itself has the following three components –
 ALU (Arithmetic Logic Unit) :
This unit consists of two subsections namely, Arithmetic Section and Logic Section
Arithmetic Section: Function of arithmetic section is to perform arithmetic operations
like addition, subtraction, multiplication, and division. All complex operations are
done by making repetitive use of the above operations.
Logic Section: Function of logic section is to perform logic operations such as
comparing, selecting, matching, and merging of data.
Memory Unit or Storage Unit: This unit can store instructions, data, and intermediate
results. This unit supplies information to other units of the computer when needed.
Memory is also known as internal storage unit or the main memory or the primary
storage or Random Access Memory (RAM).
Its size affects speed, power, and capability.
Primary memory and secondary memory are two types of memories in the computer.
Functions of the memory unit are −
SIVA SIVNI DEGREE COLLEGE 17 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 It stores all the data and the instructions required for processing.
 It stores intermediate results of processing.
 It stores the final results of processing before these results are released to an output
device.
 All inputs and outputs are transmitted through the main memory.
Control Unit:
This unit controls the operations of all parts of the computer but does not carry out
any actual data processing operations.
Functions of this unit are −
 It is responsible for controlling the transfer of data and instructions among other units
of a computer.
 It manages and coordinates all the units of the computer.
 It obtains the instructions from the memory, interprets them, and directs the
operation of the computer.
 It communicates with Input / Output devices for transfer of data or results from
storage.
 It does not process or store data.
Output Unit :The output unit consists of devices with the help of which we get the
information from the computer. This unit is a link between the computer and the
users. Output devices translate the computer's output into a form understandable by
the users.
INPUT DEVICES
Input unit is a unit that accepts any input device. The input device is used to input
data into thecomputer system.
Function of input unit:
 It converts inputted data into binary codes.
 It sends data to main memory of computer
Insertion point: A digit I will be displayed in the serial number column and a small
vertical line called a cursor (or insertion point)
Input Unit:
The input unit is used for entering the data and instruction into the computer for
performing computation of the data. The input unit accepts or reads the list of
instructions and data and converts these instructions and data in computer
acceptable form. It supplies the converted instructions and data to the computer for
further processing.
The devices used for this purpose are called as Input Devices. Key Board and Mouse
are the important input devices used in our offices. Light pen, Joy stick, tracker ball,
Touch pad, Scanner and Pointing stick are some of the Input Devices.
Commonly Used Input Devices
*Keyboard devices *Point-and-draw devices *Data scanning devices
*Digitizer *Electronic cards-based devices *Speech recognition devices
*Vision based devices
WRITE A SHORT NOTE ON KEYBOARD
 Is the most common way to enter text and data into a computer
 Standard layout is basically like old typewriter keyboard (called a QWERTY keyboard)
The most commonly used keyboards are
 101 – Key enhanced keyboard, 104 – key windows keyboard.
 82 – Key Apple standard keyboard and 108- key Apple extended keyboard.
 It contains alphabets (A to Z or a to z), digits (0 to 9), special characters (!@,#,$,
SIVA SIVNI DEGREE COLLEGE 18 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
%,^,&,*,<,>,? etc) and some control keys.
There are five key groups:
 Alphanumeric keys
 Letters of the alphabets
 Numbers and symbols
 Caps lock, tab, backspace and enter key do special functions but they arepart of the
alphanumeric key group.
 Modifier Key group
 Modify what happens when you press another key
 Shift changes letter keys to upper case
 Shift makes the number keys produce special symbols
 Ctrl and alt used in combination with other keys change what that key does
 Numeric Key Pad
 Looks like a calculator keyboard
 Used to enter numbers and operation symbols
 Num lock forces keypad to enter numbers which is the normal default.
 Function Keys
 Middle of top row
 Labeled F1 to F12
 Could be assigned specific commands by the current application oroperating
system (or software dependent)
 Cursor Movement keys
 Direct movement of on-screen cursor
 Up, down, left and right arrow
 Other keys are insert, home, page up, delete, end and page down
 Special purpose keys are in addition to the five key group are found on keyboards
specificallydesigned for windows operating system
 Start key or windows key
When a key is pressed an electronic signal is produced which is detected by an
electronic circuitcalled keyboard encoder or controller.

Types of Keyboard Layouts: Based on Alphanumeric keys keyboards are available


in 2 different layouts.
They are QWERTY and DVORAK.
QWERTY Layout: It was invented during the 19th century i.e. in the area of
mechanical typewriters.

SIVA SIVNI DEGREE COLLEGE 19 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
This layout was adopted by most of the people. QWERTY name was taken by the
first 6 letters that appear in left most position in the top row of the alphabetical
keypad of keyboard.

Features of QWERTY Keyboard:


Commonly used layout on mechanical typewriters.
Commonly used layout for English language.
It is basically preferred for inexperience people or beginners.
It has the capability to reducing the key jamming.
DVORAK Layout: It is an alternative to QWERTY layout. It is the best layout. It
reduces the finger travel distance. It increases the typing speed from 150 wpm to 200
wpm. WPM stands for Words Per Minute.

Features of DVORAK Keyboard:


Frequently used keys are placed on home row.
User compatibility is more.
Reducing the finger work up to 24%.
Increasing the typing speed.
WRITE A SHORT NOTE ON POINT-AND-DRAW DEVICES:
 Used to rapidly point to and select a graphic icon or menu item from multiple
options displayed on the Graphical User Interface (GUI) of a screen
 Used to create graphic elements on the screen such as lines, curves, and freehand
shapes
 Some commonly used point-and-draw devices are mouse, track ball, joy stick, light
pen, and touch screen
MOUSE: Mouse is a pointing device.
 Is a small hand-held device used to position the cursor on the screen and a kind of pointing
device
 Is an input device that rolls around on a flat surface and controls the pointer
 Pointer is an on-screen object, usually an arrow, that is used to select text; access menus;
andinteract with programs, files or data that appear on the screen.
Mouse Actions:
 Clicking – move pointer to item and click left button one time.
 Double – clicking – move pointer to item and click left button two times quickly.
 Dragging – position mouse over item, click and hold left button as you move the mouse.
 Right Click – move pointer to item and click one time with right button

SIVA SIVNI DEGREE COLLEGE 20 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
o Mouse moves across a monitor screen.
o Itis a very famous cursor-control device having a small palm size box with a round
ball at its base, which senses the movement of the mouse and sends corresponding
signals to the CPU when the mouse buttons are pressed.
o Mouse contains 2 buttons named as LMB (Left Mouse Button) and RMB (Right
Mouse Button).
o Mouse has 1 wheel named as Scroll Wheel used to move up and down of a screen.

The different types of mouse are, (i) Mechanical mouse (ii) Opt mechanical mouse
(iii) Optical mouse.
1. Mechanical Mouse: Mechanical mouse is one of the simple types of mouse
which was used by the computer users earlier. It consists of a small round shape
rubber ball and two fly wheels. The rubber ball is present at the bottom which comes
in contact with a mouse pad.
2. Opt mechanical Mouse: Opt mechanical mouse is an alternative to mechanical
mouse. It uses rollers and LED photodiode instead of wire mesh that is used in
mechanical mouse. It consists of a ball, LED, photodiode and two rollers.
3. Optical Mouse: Basic Computer Skills Optical mouse is quite opposite of
mechanical mouse. It does not have any moving parts as that of mechanical mouse.
It makes use of lasers or LEDs for detecting the movement of mouse.
The optical mouse mainly comprises the components such as inbuilt optical sensor,
high speed camera and Light Emitting Diodes (LED).
The optical mouse contains in-built optical sensors that are used for reading its
movements. The movements are read by means of light rays coming out from LEDs
(Light Emitting Diodes).

Joy sticks: Commonly used for video games, flight simulators, training simulators,
and for controlling industrial robots

SIVA SIVNI DEGREE COLLEGE 21 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Joystick is also a pointing device, which is used to


move the cursor position on a monitor screen. It is a
stick having a spherical ball at its both lower and upper
ends. The lower spherical ball moves in a socket.
The joystick can be moved in all four directions. The
function of the joystick is similar to that of a mouse. It is mainly used in Computer
Aided Designing (CAD) and playing computer games.
(electric) Light Pen: Light pen is a pointing device similar to a pen. It is used to select
a displayed menu item or draw pictures on the monitor screen.
It consists of a photocell and an optical system placed in a small tube. When the tip
of a light pen is moved over the monitor screen and the pen button is pressed, its
photocell sensing element detects the screen location and sends the corresponding
signal to the CPU.
Track Ball: Track ball is an input device that is mostly used in notebook or laptop
computer, instead of a mouse. This is a ball which is half inserted and by moving
fingers on the ball, the pointer can be moved. Since the whole device is not moved, a
track ball requires less space than a mouse. A track ball comes in various shapes like
a ball, a button, or a square.

Touch Screen:
 Most simple, intuitive, and easiest to learn of all input Devices
 Enables users to choose from available options by simply touching with their finger
the desired icon or menu item displayed on the screen
 Most preferred human-computer interface used in information kiosks (unattended
interactive information systems such as automatic teller machine or ATM)
Data Scanning Devices
 Input devices that enable direct data entry into a computer system from source
documents
 Eliminate the need to key in text data into the computer
 Due to reduced human effort in data entry, they improve data accuracy and also
increase the timeliness of the information processed
 Demand high quality of input documents
 Some data scanning devices are also capable of recognizing marks or characters
 Form design and ink specification usually becomes
more critical for accuracy
1. Image Scanner
 Input device that translates paper documents into
an electronic format for storage in a computer
 Electronic format of a scanned image is its bit map
representation and Stored image can be altered or
manipulated with an image-processing software
DEFINE SCANNER: Scanner is an input device, which works more like a photocopy
machine. Scanner captures images from the source which are then converted into a
digital form that can be stored on the disk. These images can be edited before they
are printed.

SIVA SIVNI DEGREE COLLEGE 22 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Scanners are 2 types. They are Flat-bed scanner and Hand-held scanner.
Flat-bed Scanner: Flat-bed scanner is one of the most commonly used input devices
for scanning the documents. It is similar to a Xerox machine. It is a box that consists
of a transparent glass plate at the top and a covering lid.
In a flat-bed scanner, a document can be scanned by placing it on to the glass-plate
and closing the lid.
This document is then enlightened by using a lamp (i.e., Cold Cathode Fluorescent
Lamp (CCFL) is mostly preferred). A scan head (or scanner head) consists of mirrors,
lens, CCD (Charge Coupled Device) and filters.
Hand-held Scanner: Hand-held scanner carries a set of LEDs. To scan a page, user
needs to manual hold the scanner in the hand and slowly drag it over the page. The
quality of scanning completely relies on the steadiness of scanning. For this reason,
it is less preferable over flat-bed scanners.
Optical Character Recognition (OCR) Device
 Scanner equipped with character recognition software (called OCR software) that
converts the bit map images of characters to equivalent ASCII codes
 Enables word processing of input text and also requires less storage for storing the
document as text rather than an image
 OCR software is extremely complex because it is difficult to make a computer
recognize an unlimited number of typefaces and fonts
 Two standard OCR fonts are OCR-A (American standard) and OCR-B (European
standard)
 Optical character recognition, usually abbreviated to OCR, is the mechanical or
electronic translation of images of handwritten, typewritten or printed text (usually
captured by a scanner) into machine-editable text.
 OCR is used for reading text from paper and translating the images into a form that
the computer can manipulate (e.g. into ASCII code)
 Scans the documents and using the photo electric device converts the shape into
electric signals.
 These patterns are then compared with the stored patterns of the characters which
the reader can recognize
 If a match is found, the character scanned is identified otherwise the document
may be rejected by the reader.

Optical Mark Reader ((OMR))


 Scanner capable of recognizing a pre-specified type of mark by pencil or pen
 Very useful for grading tests with objective type questions, or for any input data
that is of a choice or selection nature
SIVA SIVNI DEGREE COLLEGE 23 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 Technique used for recognition of marks involves focusing a light on the page being
scanned and detecting the reflected light pattern from
the marks
Magnetic--Ink Character Recognition ((MICR))
 MICR is used by banking industry for faster processing
of large volume of cheques
 Bank’s identification code (name, branch, etc.), account
number and cheques number are pre-printed (encoded)
using characters from a special character set on all
cheques
 Special ink is used that contains magnetizable particles of iron oxide
 MICR reader-sorter reads data on cheques and sorts them for distribution to other
banks or for further processing
 Magnetic Ink Character Reader (MICR) checks the legitimacy of the paper
documents, such as bank checks.
 It has magnetic ink printed characters that are captured by the high-speed magnetic
recognition devices.
 They provide some important information to the receivers for processing.
 They promote security and speed up in the document sorting process.
 They decrease the chances of check fraud.
Bar--code Reader
 Is an electronic device for reading printed barcodes.
 Consists of a light source, a lens and a photo
conductor translating optical impulses into electrical
ones.
 Is used to extract the information of any product, its
description, date of manufacture and expiry and
price.
 Scanner uses laser-beam to stroke across pattern of bar code.
Different patterns of bars reflect the beam in different ways sensed by a light-
sensitive detector
Universal Product Code (UPC) is the most widely known bar coding system
Digitizer device
Input device used for converting (digitizing) pictures, maps and drawings into digital
form for storage in computers
Commonly used in the area of Computer Aided Design (CAD) by architects and
engineers to design cars, buildings medical devices, robots, mechanical parts, etc.
Used in the area of Geographical Information System (GIS) for digitizing maps
available in paper form

Electronic--card Reader
 Electronic cards are small plastic cards having encoded data appropriate for the
application for which they are used

SIVA SIVNI DEGREE COLLEGE 24 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 Electronic-card reader (normally connected to a computer) is used to read data
encoded on an electronic card and transfer it to the computer for further processing
 Used together as a means of direct data entry into a computer system
 Used by banks for use in automatic teller machines (ATMs) and by organizations for
controlling access of employees to physically secured areas.

Webcam: Webcam is an abbreviation of Web Camera. It is a portable video camera


which is responsible for capturing live images/ videos and streaming them in real
time to a computer. This captured image/ videos can be watched over the internet.
This device is similar to digital camera and usually built into computer hardware like
laptop. Web cams are 2 types. They are streaming webcam and Snapshot webcam.

Voice Recognition Systems

 Speech/voice recognition systems are used for capturing or creating


the sound such as music, speech, etc. They allow the users to input the
data to the computer through their speech/voice.
 They make use of microphones for this purpose.
 It requires the input to be given in a proper way with appropriate accent,
vocabulary and grammar.
 This makes it a less preferable and complex system.
Vision Input Systems
Vision input or video input system allows the users to provide input to the system in
the form of a visual or video format. This system recognizes various shapes and
attributes of objects to recognize them. The input is given from a video camera and
the computer performs the following activities,
 Captures a picture of the object by focusing on it.
 Creates a digital image and stores it in the computer.
 Matches the captured image with the images present in its database.
 Performs a specific action based on the match results.
The system is getting a highly adopted robot that uses artificial intelligence
technology.

SIVA SIVNI DEGREE COLLEGE 25 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Touch Pad (Track Pad)
 It is a pointing device consisting of specialized surface that can translate the motion and
position of a user's fingers to a relative position on screen.
 They are a common feature of laptop computers and
 Also used as a substitute for a computer mouse where desk spaceis scarce.
 Touch pads vary in size but are rarely made larger than 40square centimeters (about 6
square inches). They can also befound on personal digital assistants (PDAs) and some
portable media players.
OUTPUT DEVICES
The output could be on a paper or on a film in a tangible form, or, in an intangible
form as audio, video and electronic form. Output devices are classified as follows—
Hard Copy Devices
o Printer
o Plotter
o Computer Output on Microfilm (microfiche)
Soft Copy Devices
o Monitor
o Visual Display Terminal
o Video Output
o Audio Response
HARD COPY DEVICES
The output obtained in a tangible form on a paper or any surface is called hard copy
output. The hard copy can be stored permanently and is portable.
The hard copy output can be read or used without a computer. The devices that
generate hard copy output are called hard copy devices. Printer, plotter and
microfiche are common hard copy output devices.

PRINTER
 A printer prints the output information from the computer onto a paper. Printers are
generally used to print textual information, but nowadays printers also print
graphical information.
 The print quality (sharpness and clarity of print) of the printer is determined by the
resolution of the printer.
 Resolution is measured in dots per inch (dpi). Printers with a high resolution (more
dpi) provide better quality output. Different kinds of printers are available for
different types of applications.
Printers are classified into two categories—impact printer and non-impact printer.
Impact printers use the typewriter approach of physically striking a typeface against
the paper and inked ribbon. Impact printers can print a character or an entire line at
a time. Impact printers are low-cost printers useful for bulk printing.

Characteristics of Impact Printers are the following −


 Very low consumable costs AND very noisy
 Useful for bulk printing due to low cost
 There is physical contact with the paper to produce an image
 Dot matrix printers, daisy wheel printers and drum printers are examples of impact
printers.
Dot Matrix Printers
 Print one character at a time. The speed of dot matrix printer lies between 200
and 600 characters persecond (cps) and their resolution ranges from 72 to 360 dpi.

SIVA SIVNI DEGREE COLLEGE 26 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 Dot matrix printers normally come in two sizes—80 column printer and 132 column
printers.
 Dot matrixprinters can print alphanumeric characters, special characters, charts and
graphs.
 They can print only in black and white. Some dot matrix printers can print in both
directions - left to right and right to left.
 Dot matrix printers are commonly used for printing in applications like payroll and
accounting.

 Dot Matrix Printer is an impact printer. The


characters and images printed by it are the
patterns of dots. These patterns are produced
by striking the ink-soaked ribbon against the
paper with a print head.
 The print head contains pins that produce a
pattern of dots on the paper to form the
individual characters. The print head of a 24-
pin dot matrix contains more pins than a 9-pin
dot matrix printer, so it produces more dots
which results in better printing of characters.To produce color output, the black
ribbon can be changed with color stripes.
Drum Printers are line printers:
 Line printer, which is also as a bar printer, prints one line at a time. It is a high-
speed impact printer as itcan print 500 to 3000 lines per minute.
 Drum printer and chain printer are examples of line printers.
 They are expensive and faster than character printers but produce a low-quality
output. Drum printers are generally used for voluminous print outputs.
 Drum printer is a line printer that is made of a rotating drum to print characters. The
drum has circular bands of characters on its surface. It has a separate hammer for
each band of characters.
 When you print, the drum rotates, and when the desired character comes under
the hammer, the hammer strikes the ink ribbon against the paper to print
characters. The drum rotates at a very high speed and characters are printed by
activating the appropriate hammers.
 Although all the characters are not printed at a time, they are printed at a very high
speed. Furthermore, it can print only a predefined style as it has a specific set of
characters.
 These printers are known to be very noisy due to the use of hammering techniques.

Non-Impact Printers do not hit or impact a ribbon to print. They use electro-static
chemicals and ink-jet technologies. Non-impact printers are faster and quieter than
impact printers.

SIVA SIVNI DEGREE COLLEGE 27 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
They produce high quality output and can be used for printing text and graphics both
in black and white, and color.Non-impact printers print the characters without using
the ribbon. These printers print a complete page at a time, thus they are also called as
Page Printers.
These printers are of two types −Laser Printers *Inkjet Printers
Characteristics of Non-impact Printers
 Faster than impact printers
 They are not noisy
 High quality
 Supports many fonts and different character size
Laser printers
 A laser printer is a non-impact printer that uses a laser beam to print the
characters. The laser beam hits thedrum, which is a photoreceptor and draws the
image on the drum by altering electrical charges on the drum.
 The drum then rolls in toner, and the charged image on the drum picks the toner.
 The toner is then printed on the paper using heat and pressure. Once the
document is printed, the drum losesthe electric charge, and the remaining toner is
collected.
 The laser printers use powdered toner for printing instead of liquid ink and
produce quality print objects with aresolution of 600 dots
per inch (dpi) or more.
Advantages
 Very high speed
 Very high-quality output
 Good graphics quality
 Supports many fonts and different character size
Disadvantages
 Expensive *Cannot be used to produce multiple copies of
a document in a single printing
Ink-jet printer
 The inkjet printer is a non-impact printer that prints images and characters by
spraying fine, ionized drops ofink. The print head has tiny nozzles to spray the
ink.
 The printer head moves back and forth and sprays ionized drops of ink on the
paper, which is fed through theprinter.
 These drops pass through an electric field that guides the ink onto the paper
to print correct images andcharacters.
 An inkjet printer has cartridges that contain ink.
 Modern inkjet printers are color printers that have fourcartridges containing
different colors: Cyan, Magenta, Yellow, and Black.
 It is capable of printing high-quality images with different colors. It can produce
print objects with a resolutionof at least 300 dots per inch (dpi).
Advantages
 High quality printing
 More reliable
Disadvantages
 Expensive as the cost per page is high
 Slow as compared to laser printer
Choosing a printer
You might be wondering what printer to purchase as there are literally plenty of

SIVA SIVNI DEGREE COLLEGE 28 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
options to consider. Becauseof numerous products in the same price range, making
the right choice has become quite challenging.
The right choice can be made by looking for the right factors to consider when
purchasing a printer to fulfill relevant needs.
 Technology Connectivity
 Type of Printer and Printing Speed
 Running Cost and Resolution
 Duplex Printing and Printer Size
 Needed Functions and Media Handling
 Monochrome vs. Color
Soft Copy Devices
The output obtained in an intangible form on a visual display, audio unit or video
unit is called soft copy output. The soft copy allows corrections to be made, can be
stored, and, can be sent via E– to other users.
The soft copy output requires a computer to be read or used. The devices that generate
soft copy output are called soft copy devices. Visual output devices like computer
monitor, visual display terminal, video system and audio response system are
common soft copy output devices.
Monitor
Monitor is a common output device. The monitor is provided along with the
computer, to view the displayed output. A monitor is of two kinds - monochrome
display monitor and color display monitor.
A monochrome display monitor uses only one color to display text and color display
monitor can display 256 colors at one time. The number of colors displayed by a color
monitor varies with the kind of color adapter attached to it— CGA, EGA, VGA, XGA
and SVGA. The CGA monitor supports four colors and SVGA supports around
16,000,000 colors. Monitors are available in various sizes like 14, 15, 17, 19 and 21
inches.
An image on the monitor is created by a configuration of dots, also known as pixels.
The clarity of image on the computer screen depends on three factors—
1. Resolution of Screen—the number of pixels in horizontal and vertical direction.
More the number of pixels,the sharper are the image. The common resolution of
computer screen is 800x600 and 1024x768,
2. Dot Pitch—the diagonal distance between two colored pixels on a display screen,
3. Refresh Rate—the number of times per second the pixels are recharged so that their
glow remains bright. Monitors may be Cathode Ray Tube (CRT) monitors that
look like a television or Liquid Crystal Display(LCD) monitors that have a high
resolution, flat screen, flat panel display.
CRT monitors are based on the cathode ray tubes.
 They are like vacuum tubes which produce images in the form of video signals.
Cathode rays tube produces a beam of electrons through electron guns that strike
on the inner phosphorescent surface of the screen to produce images on the screen.
 The monitor contains millions of phosphorus dots of red, green and blue color. These
dots start to glow when struck by electron beams and this phenomenon is called
cathodoluminescence.
 The main components of a CRT monitor include the electron gun assembly,
deflection plate assembly, fluorescent screen, glass envelope, and base. The front
(outer surface) of the screen onto which images are produced is called the face plate.
It is made up of fiber optics.
 There are three electron beams that strike the screen: red, green, and blue.

SIVA SIVNI DEGREE COLLEGE 29 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 So, the colors which you see on the screen are the blends of red, blue and green lights.
 The magnetic field guides the beams of electrons.
 Although LCDs have replaced the CRT monitors, the CRT monitors are still used by
graphics professionalsbecause of their color quality.

Flat-Panel Display Monitor


The flat-panel display refers to a class of video devices that have reduced volume,
weight and power requirement in comparison to the CRT.
You can hang them on walls or wear them on your wrists. Current usesof flat-panel
displays include calculators, video games, monitors, laptop computer, and graphics
display.
The flat-panel display is divided into two categories −
 Emissive Displays − Emissive displays are devices that convert electrical energy into
light. For example,plasma panel and LED (Light-Emitting Diodes).
 Non-Emissive Displays − Non-emissive displays use optical effects to convert
sunlight or light from someother source into graphics patterns. For example, LCD
(Liquid-Crystal Device).
LCD MONITOR
 The LCD monitor is a flat panel screen that is compact and light-weight as compared
to CRT monitors.
 It is based on liquid crystal display technology which is used in the screens of
laptops, tablets, smart phones,etc. An LCD screen comprises two layers of polarized
glass with a liquid crystal solution between them.
 When the light passes through the first layer, an electric current aligns the liquids
crystals.
 The aligned liquid crystals allow a varying level of light to pass through the second
layer to create images onthe screen.
 The LCD screen has a matrix of pixels that display the image on the screen.
 Old LCDs had passive-matrix screens in which individual pixels are controlled by
sending a charge.
 A few electrical charges could be sent each second that made screens appear blurry
when the images movedquickly on the screen.
 Modern LCDs use active-matrix technology and contain thin film transistors (TFTs)
with capacitors.
 This technology allows pixels to retain their charge.So, they don’t make screen blurry
when images move fast on the screen as well as are more efficient thanpassive-
matrix displays.

SIVA SIVNI DEGREE COLLEGE 30 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
AUDIO OUTPUT
 A sound card is an internal expansion card that provides input and output of audio
signals to and from a computer under control of computer programs.
 The sound card can accept an analog sound (as from a microphone or audio tape)
and convert it to digital data that can be stored in an audio file, or it can accept
digitized audio signals (as from an audio file) and convert them to analog signals that
can be played on the computer's speakers.
 On personal computers, the functions of a sound card are usually directly integrated
into the motherboard,but, for those who desire higher-quality audio, a sound card is
a separate circuit board that is plugged into themotherboard.
Text-to-Speech (TTS)
 Text-to-speech (TTS) is a type of assistive technology that reads digital text aloud. It’s
sometimes called ―read aloud‖ technology.
 With a click of a button or the touch of a finger, TTS can take words on a computer or
other digital deviceand convert them into audio

.
Speech-To-Text (STT)
 Speech to text is speech recognition software that enables the recognition and
translation of spoken language into text through computational linguistics. It is also
known as speech recognition or computer speech recognition. Specific applications,
tools, and devices can transcribe audio streams in real-time to display text and act on
it.
 Speech to text is software that works by listening to audio and delivering an editable,
verbatim transcript on a given device. The software does this through voice
recognition.
COMPUTER MEMORY HIERARCHY
 A memory is just like a human brain. It is used to store data and instructions.
Computer memory is the storage space in the computer, where data is to be processed
and instructions required for processing are stored.
 The memory is divided into large number of small parts called cells. Each location or
cell has a unique address, which varies from zero to memory size minus one.
 For example, if the computer has 64k words, then this memory unit has 64 * 1024 =
65536 memory locations. The address of these locations varies from 0 to 65535.
MEMORY HIERARCHY
 The memory is characterized on the basis of two key factors—capacity and access
time. Capacity is the amount of information (in bits) that a memory can store. Access
time is the time interval between the read/ write request and the availability of data.
The lesser the access time, the faster is the speed of memory.
 Ideally, we want the memory with fastest speed and largest capacity. However, the
cost of fast memory is very high. The computer uses a hierarchy of memory that is
organized in a manner to enable the fastest speed and largest capacity of memory.
 The hierarchy of the different memory types is shown in

SIVA SIVNI DEGREE COLLEGE 31 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Secondary/ Auxiliary Memory : Auxiliary memory is much larger in size than main
memory but is slower. It normally stores system programs, instruction and data files.
It is also known as secondary memory. It can also be used as an overflow/virtual
memory in case the main memory capacity has been exceeded. Secondary memories
cannot be accessed directly by a processor. First the data/information of auxiliary
memory is transferred to the main memory and then that information can be accessed
by the CPU.
Main Memory : The main memory occupies the central position because it is
equipped to communicate directly with the CPU and with auxiliary memory devices
through Input/output processor (I/O).
Cache Memory : It is small in size but faster than the main memory. The CPU can
access it more quickly than the primary memory. It holds the data and programs
frequently used by the CPU. So if the CPU finds the required data or instructions in
cache memory it doesn't need to access the primary memory (RAM). Thus, it speeds
up the system performance.
Register Memory : Register memory is the smallest and fastest memory in a
computer. It is located in the CPU in the form of registers. A register temporarily holds
frequently used data, instructions and memory address that can be quickly accessed
by the CPU.
Memory Units :
1) The memory’s interface circuit is designed to logically access a byte or a multiple
of a byte of data from the memory during each access.
2) The smallest block of memory is considered to be a byte, which comprises eight
bits. The total memory space is measured in terms of bytes. Thus, the unit of
memory is a byte.
3) The capacity of memory is the maximum amount of information it is capable of
storing.

Memory units are used to measure and represent data. Some of the commonly
used memory units are:
 Bit: The computer memory units start from bit. A bit is the smallest memory unit
to measure datastored in main memory and storage devices. A bit can have only
one binary value out of 0 and 1.
 Byte: It is the fundamental unit to measure data.
 It contains 8 bits or is equal to 8 bits. Thus a bytecan represent 2*8 or 256 values.
 Kilobyte: A kilobyte contains 1024 bytes.
SIVA SIVNI DEGREE COLLEGE 32 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 Megabyte: A megabyte contains 1024 kilobytes.
 Gigabyte: A gigabyte contains 1024 megabyte.
Terabyte: A terabyte contains 1024 gigabytes.
BYTE = 8 BITS = 1 character/ 1 alphabet/ 1 key in keyboard
4bits-1Nibble
8bits=1Byte
1024byes= Kilobyte (KB)
Kilobyte (KB) = 1024 bytes
Megabyte (MB) = 1024 Kilobytes
Gigabyte (GB) = 1024 Megabytes
Terabyte (TB) = 1024 Gigabytes
Petabyte (PB) = 1024 Terabytes
Exabyte (EB) = 1024 Petabytes
Zettabyte (ZB) = 1024 Exabyte
Yottabyte (YB) = 1024 Zettabyte
 Memory is logically organized as a linear array of locations.
For a processor, the range of the memory addresses is 0 to the maximum size of
memory. Figure shows the organization of a 16 MB block of memory for a processor
with a 32-bit word length.

Processor Register :
 A processor register is a local storage space on a processor that holds data that is
being processed by CPU. Processor registers generally occupy the top-most position
in the memory hierarchy, providing high-speed storage space and fast access to data.
A register may include the address of the memory location instead of the real data
itself.
 Every processor has a local storage area known as a register that performs most of the
operations that the processor cannot perform directly. Any kind of data must first be
identified by the register before it can be manipulated by the processor.
 For example, if an arithmetic operation is to be performed on two numbers, the inputs
and the results are to be stored in the register. The processor registers are generally
measured in terms of bits to determine the amount of data they can hold. For example,
the two most frequently used terms, 32-bit processor’ and 64-bit processor, generally
refer to the size of the register on the processor.
Processor registers can be classified into general-purpose and special-purpose
registers.
Accumulator (ACC) stores the result of arithmetic and logic operations.
Instruction Register (IR) contains the current instruction most recently fetched.
Program Counter (PC) contains the address of next instruction to be processed.

SIVA SIVNI DEGREE COLLEGE 33 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Memory Address Register (MAR) contains the address of next location in the
memory to be accessed.
Memory Buffer Register (MBR) temporarily stores data from memory or the data
to be sent to memory.
Data Register (DR) stores the operands and any other data.
Virtual Memory
Write a short note on virtual memory?
Virtual memory is a memory management technique where secondary memory can
be used as if it were a part of the main memory. Virtual memory is a common
technique used in a computer's operating system (OS).
Virtual memory uses both hardware and software to enable a computer to
compensate for physical memory shortages, temporarily transferring data from
random access memory (RAM) to disk storage.

The advantages to using virtual memory include:


 It can handle twice as many addresses as main memory.
 It enables more applications to be used at once.
 It frees applications from managing shared memory and saves users from having
to add memory modules when RAM space runs out.
 It has increased speed when only a segment of a program is needed for execution.
 It has increased security because of memory isolation.
 It enables multiple larger applications to run simultaneously.
 Allocating memory is relatively inexpensive.
 It does not need external fragmentation.
 CPU use is effective for managing logical partition workloads.
 Data can be moved automatically.

SIVA SIVNI DEGREE COLLEGE 34 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Memory Is Primarily Of Three Types :


 Cache Memory
 Primary Memory/Main Memory
 Secondary Memory
1. Cache Memory :
Cache memory is a very high speed
semiconductor memory which can speed
up the CPU. It acts as a buffer between the
CPU and the main memory. It is used to
hold those parts of data and program which
are most frequently used by the CPU. The
parts of data and programs are transferred
from the disk to cache memory by the
operating system, from where the CPU can
access them.

 The advantages of cache memory are as follows –

SIVA SIVNI DEGREE COLLEGE 35 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 Cache memory is faster than main memory.
 It consumes less access time as compared to main memory.
 It stores the program that can be executed within a short period of time.
 It stores data for temporary use.
 The disadvantages of cache memory are as follows −
 Cache memory has limited capacity.
 It is very expensive.
2. Primary Memory (Main Memory)
Primary memory holds only those data and instructions on which the
computer is currently working. It has a limited capacity and data is lost when power
is switched off. It is generally made up of semiconductor device. These memories are
not as fast as registers.
The data and instruction required to be processed resides in the main memory.
It is divided into two subcategories RAM and ROM. Characteristics of Main Memory
 These are semiconductor memories.
 It is known as the main memory.
 Usually volatile memory.
 Data is lost in case power is switched off.
 It is the working memory of the computer.
 Faster than secondary memories.
 A computer cannot run without the primary memory.
A) RAM (Random Access Memory) : It is the internal memory of the CPU for storing
data, program, and program result. It is a read/write memory which stores data until
the machine is working. As soon as the machine is switched off, data is erased.
Access time in RAM is independent of the address, that is, each storage location
inside the memory is as easy to reach as other locations and takes the same amount
of time. Data in the RAM can be accessed randomly but it is very expensive.

RAM is volatile, i.e. data stored in it is lost when we switch off the computer or if
there is a power failure. Hence, a backup Uninterruptible Power System (UPS) is
often used with computers. RAM is small, both in terms of its physical size and in
the amount of data it can hold.
RAM is of two types −
 Static RAM (SRAM)
 Dynamic RAM (DRAM)
Static RAM (SRAM)
The word static indicates that the memory retains its contents as long as
power is being supplied. However, data is lost when the power gets down due to
volatile nature. SRAM chips use a matrix of 6-transistors and no capacitors.
Transistors do not require power to prevent leakage, so SRAM need not be refreshed
on a regular basis.SRAM is thus used as cache memory and has very fast access.
Characteristic of Static RAM
 Long life
 No need to refresh
 Faster
 Used as cache memory
 Large size
 Expensive
 High power consumption
SIVA SIVNI DEGREE COLLEGE 36 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Dynamic RAM (DRAM)
DRAM, unlike SRAM, must be continually refreshed in order to maintain the data.
This is done by placing the memory on a refresh circuit that rewrites the data several
hundred times per second. DRAM is used for most system memory as it is cheap and
small. All DRAMs are made up of memory cells, which are composed of one
capacitor and one transistor.
Characteristics of Dynamic RAM
 Short data lifetime
 Needs to be refreshed continuously
 Slower as compared to SRAM
 Smaller in size
 Less expensive and Less power consumption
SDRAM (synchronous DRAM) is a generic name for
various kinds of dynamic random access memory (DRAM) that are synchronized
with the clock speed that the microprocessor is optimized for. This tends to increase
the number of instructions that the processor can perform in a given time.
B) ROM (Read Only Memory) : The memory from which we can only read but cannot
write on it. This type of memory is non-volatile. The information is stored
permanently in such memories during manufacture. A ROM stores such instructions
that are required to start a computer. This operation is referred to as bootstrap. ROM
chips are not only used in the computer but also in other electronic items like washing
machine and microwave oven.
The various types of ROMs and their characteristics:
 MROM (Masked ROM) :
The very first ROMs were hard-wired devices that contained a pre-programmed set
of data or instructions. These kind of ROMs are
known as masked ROMs, which are inexpensive.
 PROM (Programmable Read Only Memory) :
PROM is read-only memory that can be modified
only once by a user. The user buys a blank PROM and
enters the desired contents using a PROM program.
Inside the PROM chip, there are small fuses which are
burnt open during programming. It can be
programmed only once and is not erasable.
 EPROM (Erasable and Programmable Read Only
Memory) :
EPROM can be erased by exposing it to ultra-violet light for a duration of up to 40
minutes. Usually, an EPROM eraser achieves this function. During programming, an
electrical charge is trapped in an insulated gate region. The charge is retained for
more than 10 years because the charge has no leakage path. For erasing this charge,
ultra-violet light is passed through a quartz crystal window (lid). This exposure to
ultra-violet light dissipates the charge. During normal use, the quartz lid is sealed
with a sticker.
 EEPROM (Electrically Erasable and Programmable Read Only Memory) :
EEPROM is programmed and erased electrically. It can be erased and reprogrammed
about ten thousand times.
Both erasing and programming take about 4 to 10 ms (millisecond). In EEPROM, any
location can be selectively erased and programmed. EEPROMs can be erased one
byte at a time, rather than erasing the entire chip. Hence, the process of
reprogramming is flexible but slow.

SIVA SIVNI DEGREE COLLEGE 37 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
The advantages of ROM are as follows −
 Non-volatile in nature AND Cannot be accidentally changed
 Cheaper than RAMs and Easy to test
 More reliable than RAMs AND Static and do not require refreshing
 Contents are always known and can be verified
Basis for RAM ROM
Comparison
Memory type Volatile Non-volatile
Memory 1 to 256 GB per chip 4 to 8 MB per chip
capacity
Operation type Read and Write both. Only Read.

Speed Fast Comparatively slow.


Storage type Temporary Permanent
Also referred as Primary memory Secondary memory

Presence of data The stored data in Data retained in ROM


according to RAM lost in case of even if the power is
power source power failure. turned off.

Accessibility to Processor can directly Processor cannot directly


processor access the data in RAM. access the data in ROM.

Cost High Comparatively low


Types SRAM and DRAM PROM, EPROM and
EEPROM

Secondary Memory :
This type of memory is also known as external memory or non-volatile. It is slower
than the main memory. These are used for storing data/information permanently.
CPU directly does not access these memories, instead they are accessed via input-
output routines. The contents of secondary memories are first transferred to the main
memory, and then the CPU can access it. For example, disk, CD-ROM, DVD, etc.
Characteristics of Secondary Memory
 These are magnetic and optical memories.
 It is known as the backup memory.
 It is a non-volatile memory.
 Data is permanently stored even if power is switched off.
There exists different types of secondary storage devices, each of them suitable
for a different purpose. They mainly differ in the following aspects:
 Technology used to store data
 Capacity of data they can hold
 Size of storage device
 Portability of storage device and
 Access time to stored data.
Currently the most common forms of secondary storage device are:
 Floppy disks
 Hard disks

SIVA SIVNI DEGREE COLLEGE 38 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 Optical Disks
 Magnetic Tapes.
 Solid State Devices
Sequential--access Storage Devices
 Arrival at the desired storage location may be preceded by sequencing through other
locations.Data can only be retrieved in the same sequence in which it is stored.Access
time varies according to the storage location of the information being accessed
 Suitable for sequential processing applications where most, if not all, of the data
records need to be processed one after another
 Magnetic tape is a typical example of such a storage device
Direct--access Storage Devices
 Devices where any storage location may be selected and accessed at random
 Permits access to individual information in a more direct or immediate manner
 Approximately equal access time is required for accessing information from any
storage location Suitable for direct processing applications such as online ticket
booking systems,on-line banking systems
Magnetic Tapes
 Magnetic, optical, and magneto-optical disks are typical examples of such a storage
device.
 Commonly used sequential-access secondary storage device
 Physically, the tape medium is a plastic ribbon, which is usually ½ inch or ¼ inch
wide and 50 to 2400 feet long
 Plastic ribbon is coated with a magnetizable recording material such as iron-oxide
or chromium dioxide.
 Data are recorded on the tape in the form of tiny invisible magnetized and non-
magnetized spots (Representing 1s and 0s) on its coated surface Tape ribbon is
stored in reels or a small cartridge or Cassette
Application Areas of Magnetic Tapes
The magnetic tapes are very much suitable for the following applications −
 Serial or sequential processing.
 Backing up data on tape is very cheap.
 It is applicable for the transfer of data between multiple machines.
 It is suitable for the storage of a large volume of data.

Advantages of Magnetic Tapes


 Cost − Magnetic tape is one of the low-cost storage media. Therefore, backing up
data on tape is very cheap.

SIVA SIVNI DEGREE COLLEGE 39 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 Storage capacity − It is very large.
 Portability − It is easily portable.
 Reusable − It can remove a specific data and save another data at the same place.
Therefore it can be reused.
 Inexpensive storage device
 Can store a large amount of data
 Easy to carry or transport
 Not suitable for random access data
 Slow access device
 Needs dust prevention, as dust can harm the tape
 Suitable for back-up storage or archiving
Disadvantages of Magnetic Tapes
 Access Time − Accessing a record requires accessing all the records before the
required record. So access time is very large in magnetic tape.
Types off Magnetic Tape
½- inch tape reel
½- inch tape cartridge
¼- inch streamer tape
4- mm digital audio tape (DAT)

Magnetic Disks
 Commonly used direct-access secondary storage device.
 Physically, a magnetic disk is a thin, circular plate/platter made of metal or plastic
that is usually coated on both sides with a magnetizable recording material such as
iron-oxide
 Data are recorded on the disk in the form of tiny invisible magnetized and non-
magnetized spots
 (representing 1s and 0s) on the coated surfaces of the disk
 The disk is stored in a specially designed protective envelope or cartridge, or several
of them are stacked together in a sealed, contamination-free container.
 A disk’s surface is divided into a number of invisible concentric circles called tracks
 The tracks are numbered consecutively from outermost to innermost starting from
zero to 200
 The number of tracks on a disk may be as few as 40 on small, low-capacity disks, to
several thousand on large, high-capacity disks.
 Each track of a disk is subdivided into sectors
 There are 8 or more sectors per track
 A sector typically contains 512 bytes
Floppy Disks:
 Floppy disks are a storage medium made of a thin magnetic disk. Floppy disks often
referred to as diskettes have been and are still being widely used to store data of
small size. They were widely used from the 1970s to the early 2000s. On the 3 1⁄2-
inch microfloppy, common from the late 1980s onward, storage capabilities ranged
SIVA SIVNI DEGREE COLLEGE 40 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
from the standard 1.44 MB to 200 MB on some versions.
 They are very easy to use and are portable. They consist of a flat Mylar plastic disk
that rotates within ahard plastic casing.
 Data is stored as electromagnetic charges on a metal oxide film coating the Mylar
plastic.
Floppy disks also contain a write protect
notch that can prevent writing to the
disks.
 There exist several types of floppy
disks but the most common one is the 3.5
inch floppy that can store data up to a
capacity of 1.44 megabytes, something like
400 typewritten pages.
 A floppy drive is required to access a
floppy disk.
 When the floppy is inserted in the
floppy drive, the sliding metal shutter is
opened exposing the Mylar plastic and a
read-write head moves across the exposed
disk to either store or retrieve data. Data is
recorded on the disk in closed concentric
circles known as tracks.
Hard Disks:

 Hard disk drive is made up of a series of circular disks called platters arranged one
over the other almost ½ inches apart around a spindle. Disks are made of non-
magnetic material like aluminum alloy and coated with 10-20 nm of magnetic
material.
 Standard diameter of these disks is 14 inches and they rotate with speeds varying
from 4200 rpm for personal computers to 15000 rpm for servers.
 Data is stored by magnetizing or demagnetizing the magnetic coating. A magnetic
reader arm is used to read data from and write data to the disks. A typical modern
HDD has capacity in terabytes (TB).
 Hard disks differ from floppy disk in that they have been designed to store very high
volume of data.
 Currently hard disks can store gigabytes of data (e.g. 200GB) and they are an integral
part of the computer.
 Most operating systems are stored in hard disks andall materials that you save on
your computer is stored in the hard disk.

SIVA SIVNI DEGREE COLLEGE 41 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 Similar to floppy disks, data is stored in closed concentric circles called tracks on the
platters and a harddisk may contain several platters forming hard disk packs that
increase the capacity of data that can be stored by the device.
 The metal platter is sealed inside a disk drive that protects the platter and as well
enables reading and writing to the disk. Sometimes some hard disk may fail due to a
head crash, resulting in loss of data and this is due to various reasons such as:
improper handling of hard disks, voltage surge, malfunctioning of read/write head
and more.
Optical Disks:
 An optical disk is any computer disk that uses optical storage techniques and
technology to read and write data. It is a computer storage disk that stores data
digitally and uses laser beams (transmitted from a laser head mounted on an optical
disk drive) to read and write data.
 An optical disk is primarily used as a portable and secondary storage device. It
can store more datathan the previous generation of magnetic storage media, and has
a relatively longer lifespan. Compact disks (CD), digital versatile/video disks (DVD)
and Blu-ray disks are currently the most commonly used forms of opticals.

These disks are generally used to:


 Distribute software to customers
 Store large amounts of data such as music, images and videos
 Transfer data to different computers or devices
 Back up data from a local machine
Compact Disks (CD): Compact disks are circular disks that use optical rays, usually
lasers, to read and write data. They are very cheap as you can get 700 MB of storage
space for less than a dollar.CDs are inserted in CD drives built into CPU cabinet.
They are portable as you can eject the drive, remove the CD and carry it with you.
CD-ROM
 Stands for Compact Disk-Read Only Memory.Packaged as shiny, silver color metal
disk of 5¼ inch (12cm) diameter, having a storage capacity of about 650 Megabytes
 Disks come pre-recorded and the information stored on them cannot be altered
 Pre-stamped (pre-recorded) by their suppliers, by a process called mastering
WORM Disk / CD-Recordable (CD-R)
 Stands for Write Once Read Many. Data can be written only once on them, but can
be read many times
 Same as CD-ROM and has same storage capacity.Allow users to create their own CD-
ROM disks by using a CD-recordable (CD-R) drive that can be attached to a computer
as a regular peripheral device
 Data to be recorded can be written on its surface in multiple recording sessions
 Information recorded on them can be read by any ordinary CD-ROM drive
SIVA SIVNI DEGREE COLLEGE 42 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 They are used for data archiving and for making a permanent record of data.
CD-Read/Write (CD-RW)
 Same as CD-R and has same storage capacity
 Allow users to create their own CD-ROM disks by using a CD-recordable (CD-R)
drive that can be attached to a computer as a regular peripheral device
 Data to be recorded can be written on its surface in multiple recording sessions Made
of metallic alloy layer whose chemical properties are changed during burn and erase
Can be erased and written freshly
Digital Video / Versatile Disk (DVD)
1. Looks same as CD-ROM but has capacity of 4.7 GB or 8.5 GB
2. Designed primarily to store and distribute movies
3. Can be used for storage of large data
4. Allows storage of video in 4:3 or 16:9 aspect-ratios in MPEG-2 video format using
NTSC or PAL resolution
5. Audio is usually Dolby® Digital (AC-3) or Digital Theater System (DTS) and can
be either monaural or 5.1 Surround Sound
Memory Storage Devices

USB Flash Drive (Pen Drive)


 Relatively new secondary storage device based on flash memory, enabling easy
transport of data from one computer to another
 Compact device of the size of a pen, comes in various shapes and stylish designs
and may have different added features
 It uses a technology similar to RAM, except that it is nonvolatile
 Plug-and-play device that simply plugs into a USB (Universal Serial Bus) port of a
computer treated as portable memory device that uses solid state memory rather
than magnetic fields or lasers to record data. Available storage capacities are 8MB,
16MB, 64MB, 128MB, 256MB, 512MB, and 2GB to 512GB.
Off-line Storage Memory Card (SD/MMC)
 Similar to Flash Drive but in card shape
 Plug-and-play device that simply plugs into a port of a computer, treated as
removable drive
 Useful in electronic devices like Camera, music player
 Available storage capacities are 8MB, 16MB, 64MB, 128MB, 256MB, 512MB, 1GB,
2GB to 512GB

SIVA SIVNI DEGREE COLLEGE 43 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 An electronic flash memory storage disk commonly used in consumer electronic
devices such as digital cameras, MP3 players, mobile phones, and other small
portable devices.

OPERATING SYSTEM
An operating system (OS) is a software, that manages the computer hardware, and
provides common services for execution of various application software. For
hardware functions such as input and output and memory allocation, the operating
system acts as an intermediary between application programs and the computer
hardware.
An operating system is a collection of programs that acts as an interface between the
user of a computer and the computer hardware. In fact, it provides an environment
in which a user may execute programs.
An operating system is an important part of almost every computer system that
comprises three main components:
 The hardware (memory, CPU, arithmetic-logic unit, various storage devices,
I/O, peripheral devices, etc.)
 Systems programs (operating system, compilers, editors, loaders, utilities, etc.)
 A pplication programs (database systems, business programs, etc.)

FUNCTIONS OF OPERATING SYSTEM:


1. Resource Management:
The resource management function of an OS allocates computer resources such as
CPU time, main memory, secondary storage, and input and output devices for use
2. Process Management: The operating system is responsible for the following
activities in connection with process management:
 Creating and deleting both user and system processes.
 Suspending and resuming processes.
 Providing mechanisms for process synchronization.
 Providing mechanisms for process communication.
 Providing mechanisms for deadlock handling.
3. Memory Management: The operating system is responsible for the following
activities in connection with memory management:
 Keeping track of which parts of memory are currently being used and by
whom.
 Deciding which processes and data to move into and out of memory.
 Allocating and de allocating memory space as needed
4. File – System Management:

SIVA SIVNI DEGREE COLLEGE 44 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
The operating system is responsible for the following activities in connection with
the file management:
 Creating and deleting files
 Creating and deleting directories to organize files
 Supporting primitives for manipulating files and directories.
 Mapping files onto secondary storage.
 Backing up files on stable (nonvolatile) storage media .
5) Device Management:
One of the purposes of operating system is to hide the peculiarities of specific
hardware devices from the user.
6). Data Management:
The data management functions of an OS govern the input and output of the data
and their location, storage, and retrieval.
7). Job Management:
The job management function of an OS prepares, schedules, controls, and monitors
jobs submitted for execution to ensure the most efficient processing. A job is a
collection of one or more related programs and their data.
8). Standard means of communication between user and computer:
The OS establishes a standard means of communication between users and their
computer systems. It does this by providing a user interface and a standard set of
commands that control the hardware.
TYPES OF OPERATING SYSTEM:
Various operating systems have evolved depending on the requirement and the
cost bearing capacity of the users:
1. Single user operating system
2. Multi-user operating system
3. Single tasking operating system
4. Multi-tasking operating system
5. Multi Programming operating system
6. Single processing operating system
7. Multi-processing operating system
8. Multi-threading operating system
9. Time sharing operating system
10. Network operating system
11. Real time operating system
12. Distributed operating system
13. Online operating system
14. Batch processing operating system
1. Single User Operating System:
 A single user operating system is a type of operating system (OS) that is
developed and intended for use on a computer that will only have a single
user at any given time i.e., only one person can use the machine at a time and
operating system is available to the single user at a time.
 An example of single user operating system is MSDOS (Microsoft Disk
Operating System)
Advantages:
 It is simple to design, implement and maintain
 It is relatively bug-free
 It executes with little overhead
 A computer is dedicated to one particular task at a time.

SIVA SIVNI DEGREE COLLEGE 45 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Disadvantages:
 Inefficient use of CPU time.
 Inflexible job scheduling
2. Multi-user operating system:
 A multi user operating system is a type of operating system that allows
multiple users on different computers or terminals to access a single system
with one operating system on it.
 It allows two or more users to run program at the same time. Some operating
systems permit hundred or even thousands of concurrent users.
 Such operating system is made for machines which are more commonly called
sharable machines i.e., data from one machine can be shared by other users at
other machines.
 This operating system is more complex in nature, bigger in size and more
costly as compared to single user operating system.
 Some multi user operating systems are: windows2000, windows NT and
Windows 2003.
Advantages:
 It makes better use of resources.
 It improves productivity by allowing access of resources to multi users
simultaneously.
 It reduces response time.
Disadvantages:
 It has complex configuration
 It is difficult to handle and maintain
 It requires a lot of memory to process
 It is relatively expensive than single user operating system
 It is difficult to maintain security and integrity of user programs and data.
3. Single tasking operating system:
 Single tasking operating systems are those operating systems that can process
one application at one time.
 The user can only work on one application at a time i.e., user can’t start another
application till the processing of one application has been finished by the
operating system.
 An example of single tasking, operating system is MSDOS (Microsoft Disk
Operating system).
4. Multi-tasking operating system:
 A multi-tasking operating system is a type of operating system that is capable
of running more than one application at a time. For example: at some time you
might be downloading something from internet, as well as you are writing
mail to your friend and listening music also.
 Multi-user operating systems also have the property of multitasking. It
improves the overall efficiency of the computer.
 Today, most desktop, laptop, and notebook operating systems function with
some type of multitasking operating system. Even equipment such as
Automatic Teller Machine or ATM’s still make use of some type of
multitasking system, using a series of programs to check balances and execute
the requests made by users.
 Some multitasking operating systems are: Windows2000, Windows XP,
Windows-vista and Windows NT.
Advantages:
SIVA SIVNI DEGREE COLLEGE 46 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 It increases the overall performance of the system
 It increases the overall productivity of the system
Disadvantages:
 It requires a lot of memory to execute several programs simultaneously
 Special mechanism is required to prevent interference among processes.
5. Multi-programming operating system:
 Multi-programming refers to execution of two or more different and
independent program by the same computer.
 In this two or more program resides in main memory (RAM) and are executed
concurrently. This is done by switching the CPU from one program to another
almost instantaneously.
 Since there is only one processor, there can be no true simultaneous execution
of different programs. Instead, the operating system executes part of one
program, then part of another, and so on. To the user it appears that all
programs are executing at the same time.
 Some multi-programming operating systems are: Windows2000, Windows
XP, Windows-vista and Windows NT.
Advantages:
 It increases CPU utilization
 It decreases total read time needed to execute a job.
 It increases overall throughput of a computer
Disadvantages:
 It is relatively more complicated
 It requires CPU scheduling
 Proper memory management is required
 It requires tracking of all kinds of jobs running concurrently
6. Single processing operating system/ uni-processor operating system:
 Single processing operating systems are designed to work with one
processor/CPU
 Desktop computers and laptops are generally uni-processor systems.
 These systems can manage the processing needs of a home or a small
organizations, but they are not suitable for high level designing and complex
calculations.
 Some single processing operating systems are: Windows 98, Windows-ME.
7. Multi-processing operating system:
 A multi-processing operating system allows a program to run on more than
one central processing unit (CPU).
 If one of the CPU breaks down, the other CPU will automatically takes over
its job. This is also called parallel processing.
 By allowing parallel processing of segments of program, it improves
performance of computer systems.
 Some multiprocessing operating systems are: Windows-2000, UNIX and
Linux
Advantages:
 It increases the reliability of the system
 It increases the overall productivity of the system
 It has better performance than single-processing system
 If one CPU get failed other CPU are used to do that CPU’s job.
Disadvantages:
 It is very expensive.
SIVA SIVNI DEGREE COLLEGE 47 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 It requires a lot of memory to run and execute several user programs.
 If one CPU gets failed, it affects the speed of processing
 It is relatively more complex than single-processing system.
8. Multi-Threading operating systems:
 A multi-threading operating system allows different parts of a single program to
run concurrently.
 These threads will be alternately active, on standby, suspended or destroyed,
according to the priority assigned to them or may be run simultaneously.
 Some multithreading operating systems are: Windows-2000, UNIX and Linux.
9. Time Sharing operating systems:
 Time sharing is a technique of allocation of computer resources in a time
dependent fashion to several programs simultaneously.
 It helps to provide a large number of user’s direct access to the main computer.
 In timesharing, the CPU is divided among different users on a scheduled basis.
Therefore, each user is given a brief share of the CPU time unlike multi-
programming, where CPU allocated to programs on priority basis.
 This very brief share of CPU time is called time slice or time slot or quantum, which
may vary from 10 milliseconds to 20 milliseconds. Each program gets
predetermined “time slice”.
 At end of time slice, current program is set aside and a new one starts. By rapidly
shuffling programs, illusion of several programs executing simultaneously is
created.
 The timesharing operating system keeps only a few programs in the main memory
and rest are stored in the disk storage. The program remains in hard disk until it
is not active and when CPU time is allocated to it the program is brought to the
main memory.
 This operation of transferring programs from disk storage to main memory and
back is known as swapping.
 Sometime sharing operating systems are: Windows-2000, Windows 2003,UNIX
and Linux.
Advantages:
 Provide advantage of quick response.
 Avoids duplication of software.
 Reduces CPU idle time.
 Allows the many users to execute their task simultaneously.
 It offers better utilization of resources.
Disadvantages:
 It is very difficult and expensive to develop.
 It is hard to implement
 Memory management must be provided to the system.
 It has problem of reliability
 It is difficult to maintain security and integrity of user programs and data.
 Problem of data communication.
10. Network operating system:
 Networking operating system is the software that runs on a computer, which
acts as a server.
 NOS provide the capabilities required for network operations. It enables the
sever to manage data, users, groups, security, applications, and other
networking functions.

SIVA SIVNI DEGREE COLLEGE 48 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 NOS are based on a client/server architecture in which a server enables
multiple clients to share data and resources.
 It allows remote users to connect to a network.
 It monitors the status and functionality of network elements.
 The most popular network operating systems are Microsoft Windows Server
2003, Microsoft Windows Server 2008, UNIX, Linux and Novell NetWare.
Advantages:
 It is highly stable because of Centralized servers
 It maintains security and integrity of user programs and data.
 New hardware and technology can be easily integrated into the system
 Remote access to servers is possible from different locations and types of
systems.
Disadvantages:
 It is expensive because of high cost of buying and running a server.
 Dependency on a central location for most operations
 Regular maintenance and updates are required.
11. Real Time operating system:
 A Real Time operating System is an operating system that has been developed
for real-time applications.
 It responds to input instantly
 Real time operating systems are designed to handle events as they occur.
 Real-time operating systems are commonly found and used in Robotics.
 General-purpose operating systems, such as DOS and UNIX, are not real-time
because they can take a few seconds, or even minutes, to react. "Lynx" is an
example of a real time operating system.
Advantages:
 It is easy to design and develop
 It offers maximum consumption of the system
 It relatively requires less memory space
 It is bug-free in performing tasks.
Disadvantages:
 It performs limited task and hence cannot be used for general purpose.
 It is expensive as it requires a lot of system resources.
 It uses complex algorithm.
12. Distributed operating system:
 The development of networked computers that can be linked and communicate
with each other, gave rise to distributed computing.
 A distributed operating system manages a group of independent computers and
makes them appear to be a single computer.
 Distributed computations are carried out on more than one computer
 A distributed system may have more total computing power than a mainframe.
 It allows many users access to a common data base
 It makes Human-to-human communication easier. For example, by E-mailed.
 It splits the workload over the available machines in the most cost effective
manner.
Advantages:
 Computation distribution over several processors offers high performance.
 It is reliable i.e., One machine's failure need not bring down the system.
 Computers and software can be added incrementally
 Aggregates computing power
SIVA SIVNI DEGREE COLLEGE 49 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 It offers better utilization of resources
 It facilities Human-to-human communication
 Speedup the exchange of data with one another
 Reduction of delays in data processing
Disadvantages:
 It is very difficult to maintain
 It is much more complex to setup
 It is difficult to maintain security and Integrity of user programs and data.
 It requires special software to be able to recover networking problems such as lost
messages and congestion etc which make system overloaded.
13. Online processing operating system:
 In online processing operating system, the processing is performed under the
direct control of the CPU while at the same time the user remains in
communication with the computer.
 Time Sharing is an example of online processing. As there is direct contact
with the CPU, so access and retrieval of record are quick and direct.
 The systems which employ online processing need high capacity memory, so
that user data, operating system elements and programs can be store and
accessed quickly. Moreover, as simultaneously access is there so proper
security provisions are necessary to prevent any unauthorized access.
14. Batch processing operating system:
 In earlier computers, the users didn't interact directly with the system, instead,
a user prepared job, which consisted of program, data and some control
information about the nature of the job and submit it to the computer operator.
 The operating system of such a computer had the function to transfer the
control from one job to another.
 Batch processing operating systems are ideal in situations where:
 There are large amounts of data to be processed.
 Similar data needs to be processed
 Similar processing is involved when executing the data.
 Batch processing is also known as serial, sequential, off line, or stacked job
processing. It is the most appropriate method of processing for many types of
applications such as payroll or preparation of customer statements where it is
not necessary to update information on daily basis.
Advantages:
 It increases overall performance as a new job gets started on completion of
previous job without human intervention.
 It is efficient because these use very little computer processing time to prepare
a batch of data.
 The job execution is properly organized
 It allows sharing of computer resources among many users
 It shifts the time of job processing to when the computing resources are less
busy.
Disadvantages:
 It is difficult to provide the desired priority scheduling
 Lack of interaction between the user and hence job could enter an infinite loop
 It is difficult to debug program
 Due to lack of protection scheme, one batch job can affect pending jobs.

SIVA SIVNI DEGREE COLLEGE 50 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
WRITE ABOUT OPERATIONAL OVERVIEW OF CPU
Any process executed by central processing unit is directed by the instruction. The
processing required for a single instruction is called an instruction cycle. The four step
which the CPU carries out for each machine language instruction are fetch, decode,
execute, and store.

The steps involved in the instruction cycle while


executing a program are described below.

The Program Counter (PC) is the register that keeps


track of what instruction has to be executed next.
At the first step, the instruction is fetched from
main memory and loaded into Instruction Register (IR), whose address is specified
by PC register.
 Immediately the PC is incremented so that it points to the next instruction in the
program. Once in IR, the instruction is decoded to determine the actions needed for
its execution.
 The control unit then issues the sequence of control signals that enables execution of
the instruction. Data needed to be processed by the instructions are either fetched
from a register from RAM through an address register.
 The result of the instruction is stored (written) to either a register or a memory
location. The next instruction of a program will follow the same steps.
 This will continue until there is no more instruction in the program or the computer
is turned off, some sort of unrecoverable error occurs.
Note:
A register is a single, permanent storage location within the CPU used for a
particular, defned purpose. CPU contains several important registers such as
 The program counter(PC) register holds the address of the current instruction being
executed.
 The instruction register (IR) holds the actual instruction being executed currently
by the computer. To access data in memory, CPU makes use of two internal
registers:
 The memory address register (MAR) holds the address of a memory location.
 The memory data register (MDR), sometimes known as the memory buffer register,
will hold a data value that is being stored to or retrieved from the memory location
currently addressed by the memory address register.
PROGRAM FUNDMAMENTALS
Fundamentals Of Language
 Language: a language is a media which is used to communicate each other’s.
 Programming language: is a media which is used to communicate with users and
computer hardware components to solve the given problem.
 Programming languages are used to specify or design to a software system.
 Programming means organizing program elements according to given problem.
 Program elements are the data and instructions.
 Program is a set of statements or instructions to solve a given problem.
There are 3 kinds of properties for any programming language
 The way its stores the data and instructions
 How it manipulate input and output
 The operators it uses to transfer and combine the data

SIVA SIVNI DEGREE COLLEGE 51 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
GENERATIONS OF PROGRAMMING LANGUAGE
Programming languages have been developed over the year in a phased manner.
Each phase of developed has made the programming language more user-friendly,
easier to use and more powerful. Each phase of improved made in the development
of the programming languages can be referred to as a generation. The programming
language in terms of their performance reliability and robustness can be grouped
into five different generations,

1. First generation languages (1GL)


2. Second generation languages (2GL)
3. Third generation languages (3GL)
4. Fourth generation languages (4GL)
5. Fifth generation languages (5GL)
1. First Generation Language (Machine language)
The first generation programming language is also called low-level programming
language because they were used to program the computer system at a very low
level of abstraction. i.e. at the machine level. The machine language also referred to
as the native language of the computer system is the first generation programming
language. In the machine language, a programmer only deals with a BINARY
NUMBER (0 OR 1 BITS).
Advantages of first generation language
 They are translation free and can be directly executed by the computers.
 The programs written in these languages are executed very speedily and efficiently
by the CPU of the computer system.
 The programs written in these languages utilize the memory in an efficient manner
because it is possible to keep track of each bit of data.
2. Second Generation language (Assembly Language)
The second generation programming language also belongs to the category of low-
level- programming language. The second generation language comprises assembly
languages that use the concept of MNEMONICS for the writing program. In the
assembly language, symbolic names are used to represent the opcode and the
operand part of the instruction.
Advantages of second generation language
 It is easy to develop understand and modify the program developed in these
languages are compared to those developed in the first generation programming
language.
 The programs written in these languages are less prone to errors and therefore can
be maintained with a great case.
3. Third Generation languages (High-Level Languages)
The third generation programming languages were designed to overcome the
various limitations of the first and second generation programming languages. The
languages of the third and later generation are considered as a high-level language
because they enable the programmer to concentrate ONLY ON THE LOGIC OF THE
PROGRAMS without considering the internal architecture of the computer system.
Advantages of third generation programming language
 It is easy to develop, learn and understand the program.
 As the program written in these languages are less prone to errors they are easy to
maintain.
 The program written in these languages can be developed in very less time as
compared to the first and second generation language.
Examples: FORTRAN, ALGOL, COBOL, C++, C
SIVA SIVNI DEGREE COLLEGE 52 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
4. Fourth generation language (Very High-level Languages)
The languages of this generation were considered as very high-level programming
languages required a lot of time and effort that affected the productivity of a
programmer. The fourth generation programming languages were designed and
developed to reduce the time, cost and effort needed to develop different types of
software applications.
Advantages of fourth generation languages
 These programming languages allow the efficient use of data by implementing the
various database.
 They require less time, cost and effort to develop different types of software
applications.
 The program developed in these languages are highly portable as compared to the
programs developed in the languages of other generation.
Examples: SOL, CSS, coldfusion
5. Fifth generation language (Artificial Intelligence Language)
The programming languages of this generation mainly focus on constraint
programming. The major fields in which the fifth generation programming language
are employed are Artificial Intelligence and Artificial Neural Networks
Advantages of fifth generation languages
 These languages can be used to query the database in a fast and efficient manner.
 In this generation of language, the user can communicate with the computer system
in a simple and an easy manner.
Examples: mercury, prolog
WHAT IS A PROGRAMMING LANGUAGE?
 A programming language defines a set of instructions that are compiled together to
perform a specific task by the CPU (Central Processing Unit). The programming
language mainly refers to high-level languages such as C, C++, Pascal, Ada, COBOL,
etc.
 Each programming language contains a unique set of keywords and syntax, which
are used to create a set of instructions. Thousands of programming languages have
been developed till now, but each language has its specific purpose.
 These languages vary in the level of abstraction they provide from the hardware.
Some programming languages provide less or no abstraction while some provide
higher abstraction.
 Based on the levels of abstraction, they can be classified into TWO categories:
*Low-level language *High-level language

SIVA SIVNI DEGREE COLLEGE 53 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
LOW-LEVEL LANGUAGE: The low-level language is a programming language that
provides no abstraction from the hardware, and it is represented in 0 or 1 forms,
which are the machine instructions. The languages that come under this category are
the Machine level language and Assembly language.
 Machine-level language: The machine-level language is a language that consists of
a set of instructions that are in the binary form 0 or 1. As we know that computers can
understand only machine instructions, which are in binary digits, i.e., 0 and 1, so the
instructions given to the computer can be only in binary codes.
 Creating a program in a machine-level language is a very difficult task as it is not easy
for the programmers to write the program in machine instructions. It is error-prone
as it is not easy to understand, and its maintenance is also very high.
 A machine-level language is not portable as each computer has its machine
instructions, so if we write a program in one computer will no longer be valid in
another computer.
 The different processor architectures use different machine codes, for example, a
PowerPC processor contains RISC architecture, which requires different code than
intel x86 processor, which has a CISC architecture.
 Assembly Language : The assembly language contains some human-readable
commands such as mov, add, sub, etc. The problems which we were facing in
machine-level language are reduced to some extent by using an extended form of
machine-level language known as assembly language. Since assembly language
instructions are written in English words like mov, add, sub, so it is easier to write
and understand.
 As we know that computers can only understand the machine-level instructions, so
we require a translator that converts the assembly code into machine code. The
translator used for translating the code is known as an assembler.
 The assembly language code is not portable because the data is stored in computer
registers, and the computer has to know the different sets of registers.
 The assembly code is not faster than machine code because the assembly language
comes above the machine language in the hierarchy, so it means that assembly
language has some abstraction from the hardware while machine language has zero
abstraction.
HIGH-LEVEL LANGUAGE
The high-level language is a programming language that allows a programmer to
write the programs which are independent of a particular type of computer. The high-
level languages are considered as high-level because they are closer to human
languages than machine-level languages.
When writing a program in a high-level language, then the whole attention needs to
be paid to the logic of the problem.
A compiler is required to translate a high-level language into a low-level language.
Advantages of a high-level language
 The high-level language is easy to read, write, and maintain as it is written in English
like words.
 The high-level languages are designed to overcome the limitation of low-level
language, i.e., portability. The high-level language is portable; i.e., these languages
are machine-independent.
High-level languages can further be characterized is by programming paradigm.
A programming paradigm refers to the way of problem solving that includes a set of
methodologies, theories, practices and standards. The highlevel programming
languages may also be categorized into three groups—procedural, non-procedural, and
problem oriented.
SIVA SIVNI DEGREE COLLEGE 54 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Procedural programming languages
 In procedural programming, a program is conceived as a set of logically related
instructions to be executed in order.
 In procedural programming, each program can be divided into small self-contained
program segment, each of which performs a particular task and be re-used in the
program as and when required without repeated explicit coding corresponding to the
segment.
 These sections of code are known as procedures or subroutines or functions. It also
makes it easier for programmers to understand and maintain program structure.
Non-procedural languages
These functional languages solve a problem by applying a set of functions to the initial
variables in specific ways to get the result. A program written in a functional
language
consists of a series of built-in function evaluation together with arguments to those
functions. LISP, ML, Scheme, etc.are examples of functional languages.
Problem-oriented languages
These languages provide readymade procedures or functions which are pre-
programmed. The user has to write the statements in terms of those pre-written
functions. MATLAB
is a very popular language among scientists and engineers to solve a wide class of
problems in digital signal processing, control systems, modelling of systems
described by differential equations, matrix computations, etc.
TRANSLATORS
There are three types of translators, namely Assembler,Compiler and Interpreter.
Assembler converts one assembly language statement into a single machine
language instruction.

Depending on its implementation, a high-level language employs a compiler or an


interpreter or both for translation

SIVA SIVNI DEGREE COLLEGE 55 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Loader
Loading is the process of bringing a program from secondary memory into main
memory so it can run. The system software responsible for it is known as loader.
The simplest type of loader is absolute loader which places the program into memory
at the location prescribed by the assembler. Bootstrap loader is an absolute loader
which is executed when computer is switched on or restarted to load the operating
system.

Linker
Most of the high-level languages provide libraries of subroutines or functions so that
certain common operations may be reused by system-supplied routines without
explicit coding. Hence, the machine language program produced by
the translator must normally be combined with other machine language programs
residing within the library to form a useful execution unit. This process of program
combination is called linking and the software that performs this operation is
variously known as a linker.

SIVA SIVNI DEGREE COLLEGE 56 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
The features of a programming language
influence the linking requirements of a
program. In languages like FORTRAN,
COBOL, C, all program units are translated
separately. Hence, all subprogram calls
and common variable references require
linking. Linking makes the addresses of
programs known to each other so that
transfer of control from one subprogram to
another or a main program
takes place during execution.

COMPILING,INTERPRETING, LINKING,LOADING A PROGRAM


 Before a program can be executed, it must be translated from the programming
language in which it was written (source code) to the machine instructions of the
hardware that is to execute it, and the executable program must be loaded into
main memory.
 The first phase of the process is translation from source code to machine code.
 This is done by a compiler or assembler. Of course, the compilation process
itself generally is broken into phases.
Compiling,interpreting,loading and linking of a program
 Compiling involves preprocessing, compilation, assembly,and linking.
 Preprocessing It is the first phase of C compilation. It processes include-files,
conditional compilation instructions, and macros. The C preprocessor is used to
modify the program according to the preprocessor directives in the source code.
 A preprocessor directive is a statement (such as #define) that gives the preprocessor
specific instructions on how to modify the source code. The preprocessor is invoked
as the first part of the compiler program’s compilation step. It is usually hidden
from the programmer because it is run automatically by the compiler.

SIVA SIVNI DEGREE COLLEGE 57 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Compilation It is the second step of the compiling process.It takes the output of the
preprocessor and the source code, and generates assembler source code. The
compiler examines each program statement contained in the source program and
checks it to ensure that it conforms to the syntax and semantics of the language. If
mistakes are discovered by the compiler during this phase, they are reported to the
user. The errors then have to be corrected in the source program (with the use of an
editor), and the program has to be recompiled.
Interpreting(Assembly) It is the third stage of compilation. It takes the assembly
source code and produces an assembly listing with offsets. The assembler output is
stored in an object file. After the program has been translated into an equivalent
assembly language program, the next step in the compilation process is to translate
the assembly language statements into actual machine instructions. On most systems,
the assembler is executed automatically as part of the compilation process.
The assembler takes each assembly language statement and converts it into a binary
format known as object code, which is then written into another file on the system.
This file typically has the same name as the source file under UNIX, with the last
letter an ‘o’ (for object) instead of a ‘c’. Under Windows, the suffix letters “obj”
typically replace the “c” in the filename.
Loading a program involves reading the contents of the executable file containing
the program instructions into memory, and then carrying out other required
preparatory tasks to prepare the executable for running.
Linking It is the final stage of compilation. After the program has been translated
into object code, it is ready to be linked. The purpose of the linking phase is to get the
program into a final form for execution on the computer. The functions are the part
of the standard C library, provided by every C compiler. The program may use other
source programs that were previously processed by the compiler. These functions are
stored as separate object files which must be linked to the object file. Linker handles
this linking.
The process of compiling and linking a program is often called building. The final
linked file, which is in an executable object code format, is stored in another file on
the system ready to be run or executed. Under UNIX, this file is called a.out by
default. Under Windows, the executable file usually has the same name as the source
file, with the .c extension replaced by an exe extension.
SIVA SIVNI DEGREE COLLEGE 58 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Executing the Program: When the program is executed, each of the statements of the
program is sequentially executed. If the program requests any data from the user,
known as input, the program temporarily suspends its execution so that the input
can be entered. Or,
the program might simply wait for an event, such as a mouse being clicked, to occur.
Results that are displayed by the program, known as output, appear in a window,
sometimes called the console. Or, the output might be directly written to
a file on the system.
Write About Developing A Program
When we want to develop a program by using any programming language, we have
to follow a sequence of steps. These steps are called phases in program development.
The program development life cycle is a set of steps or phases which are used to
develop a program in any programming language.
Phases Of Program Development
Program development life cycle contains 6 phases, which are as follows –
 Problem Definition.
 Problem Analysis.
 Algorithm Development.
 Coding & Documentation.
 Testing & Debugging.
 Maintenance.

These six phases are depicted in the


diagram given below −
Problem Definition
Here, we define the problem statement
and decide the boundaries of the
problem.
In this phase, we need to understand
what is the problem statement, what is
our requirement and what is the output
of the problem solution. All these are
included in the first phase of program
development life cycle.

Problem Analysis
Here, we determine the requirements like variables, functions, etc. to solve the
problem. It means that we gather the required resources to solve the problem, which
are defined in the problem definition phase. Here, we also determine the bounds of
the solution.
Algorithm Development
Here, we develop a step-by-step procedure that is used to solve the problem by using
the specification given in the previous phase. It is very important phase for the
program development. We write the solution in step-by-step statements.
Coding & Documentation
Here, we use a programming language to write or implement the actual
programming instructions for the steps defined in the previous phase. We construct
the actual program in this phase. We write the program to solve the given problem
by using the programming languages like C, C++, Java, etc.

SIVA SIVNI DEGREE COLLEGE 59 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Testing & Debugging
In this phase, we check whether the written code in the previous step is solving the
specified problem or not. This means, we try to test the program whether it is solving
the problem for various input data values or not. We also test if it is providing the
desired output or not.
Maintenance
In this phase, we make the enhancements. Therefore, the solution is used by the end-
user. If the user gets any problem or wants any enhancement, then we need to repeat
all these phases from the starting, so that the encountered problem is solved or
enhancement is added.
OR
We first discuss the step-by-step listing of the procedure involved in creating a
computer program. Here we explain the important steps towards creating effective
programs:
definition, design, coding, testing, documentation, implementation, and
maintenance.
1. The first step in developing a program is to define the problem. This definition
must include the needed output, the available input, and a brief definition of how
one can transform the available input into the needed output.
2. The second step is to design the problem solution. This detailed definition is an
algorithm, a step-by-step procedure for solving a problem.
3. The third step in developing a program is to code the program; that is, state the
program’s steps in the language being used. The instructions must follow the
language’s syntax, or rules, just as good English must follow the rules of grammar
in English.
4. The fourth step is to test the program to make sure that it will run correctly, no
matter what happens. If the algorithm is wrong or the program does not match the
algorithm, the errors are considered logic errors. Errors in a program are called bugs;
the process of finding
the bugs and correcting them is called debugging the program. To test or debug a
program, one must create a sample-input data that represents every possible way to
enter input.
5. The fifth step in developing a program is to complete the documentation of the
program. Documentation should include: user instructions, an explanation of the
logic of the program, and information about the input and output. Documentation
is developed throughout the program development process. Documentation is
extremely important, yet it is the area in program development that is most often
overlooked or downplayed.
6. The last step in developing a program is implementation. Once the program is
complete, it needs to be installed on a computer and made to work properly. If the
program is developed for a specific company, the programming team may be
involved in implementation. If the program is designed to be sold commercially, the
documentation will have to include directions for the user to install the program and
begin working with it.
7. Even after completion, a program requires attention. It needs to be maintained
and evaluated for possible changes.

SIVA SIVNI DEGREE COLLEGE 60 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Explain About Software Development
 Programming is an individual’s effort and requires no formal systematic
approach. Software development is more than programming. A large number of
people are involved in software
 development and it emphasizes on planned aspect of development process.
Programming is one of the activities in software development. Other activities
include requirement analysis, design, testing, deployment, maintenance etc.
 A software is built according to client’s requirements. It is driven by cost, schedule
and quality. That is, software should be developed at reasonable cost, handed
over in reasonable time.
Below the most basic steps in software development are explored.
Steps in Software development:
 The entire process of software development and implementation involves a series
of steps. Each successive step is dependent on the outcome of the previous step.
 Thus, team of software designers, developers and users are required to interact
with each other at each stage of software development so as to ensure that the end
product is as per the client’s requirements.
Software development steps are:
1. Feasibility study(Planning)
The feasibility of developing the software in
terms of resources and cost is ascertained. In
order to determine the feasibility of software
developments, the existing system of the user
is analysed properly. The analysis done in this
step is
documented in a standard document called
feasibility report, which contains the
observations and recommendations related to
the task of software development.
2. Requirement analysis(Analysis)
In this step, the requirements related to the
software, which is to be developed, are understood. Analysing the requirements
analysis is an important step in the process of developing software.
If the requirements of the user are not properly understood, then the software is
bound to fall short of end user’s expectations. Thus, requirements analysis is
always the first step towards development of software.
3. Design
After the feasibility analysis stage, the next step is creating the architecture and
design of the new software. It involves developing a logical model or basic structure
of the new software. Design of the software is divided into two stages – system design
and detailed software design.
System design partitions the requirements to hardware or software systems. It
establishes overall system architecture. The architecture of a software system refers
to an abstract representation of that system . Architecture is concerned withmaking
sure the software system meets the requirements of the product, as well as ensuring
that future requirements can be addressed. The architecture step also addresses
interfaces between the software system and other software products, as well as the
underlying hardware or the host operating system.
Detailed design represents the software system functions in a form that can be
transformed into one or more executable programs. Specification is the task of
precisely describing the software to be written, possibly in a rigorous way.
SIVA SIVNI DEGREE COLLEGE 61 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
4. Implementation
In this step, the code for the different modules of the new software is developed. The
code for the different modules is developed according to the design specifications of
each module. The programmers in the software development team use development
tools for this purpose. An important, and often overlooked, task is documenting the
internal design of software for the purpose of future maintenance and enhancement.
5. Testing: It is basically performed to detect the prevalence of any errors in the new
software and rectify those errors. One of the reasons for the occurrence of errors or
defects in the new software is that the requirements of the client were not properly
understood.
Another reason for the occurrence of errors is the common mistakes committed by a
programmer while developing the code.
The two important activities that are performed during testing are verification and
validation.
Verification is the process of checking the software based on some predefined
specifications, while validation involves testing the product to ascertain whether it
meets the user requirements. During validation, the tester inputs different values to
ascertain whether the software is generating the right output as per the original
requirements.
6 . Deployment: The newly developed and fully tested software is installed in its
target environment. Software documentation is handed over to the users and some
initial data are entered in the software to make it operational. The users are also given
training on the software interface and its other functions.
7. Maintenance: In this phase, developed software is made operational. Users will
have lots of questions and software problems which lead to the next phase of
software development. Once the software has been deployed successfully, a
continuous support is provided to it for ensuring its full time availability.
The software may be required to be modified if the environment undergoes a
change. Maintaining and enhancing software to cope with newly discovered
problems or new requirements can take far more time than the initial development
of the software.
WHAT IS ALGORITHM? BASICS OF ALGORITHM?
 The word “algorithm” relates to the name of the mathematician Al-
khowarizmi, which means a procedure or a technique. Software Engineer
commonly uses an algorithm for planning and solving the problems.
 An algorithm is a sequence of steps to solve a particular problem or algorithm
is an ordered set of unambiguous steps that produces a result and terminates
in a finite time.
Computer scientist Niklaus Wirth stated that
Program = Algorithms + Data
DIFFERENT WAYS OF STATING ALGORITHMS
Algorithms may be represented in various ways. There are four ways of stating
algorithms.
These are as follows:
 Step-form(Algorithm)
 Pseudo-code
 Flowchart
1. In the step-form representation, the procedure of solving a problem is stated
with written statements. Each statement solves a part of the problem and these
together complete the solution.

SIVA SIVNI DEGREE COLLEGE 62 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
The step-form uses just normal language to define each procedure. Every statement,
that defines an action, is logically related to the preceding statement..
2. Pseudocode is an informal description of a sequence of steps for solving a problem.
It is an outline of a computer program, written in a mixture of a programming
language and English. Writing pseudocodes is one of the best ways to plan a
computer program.
3. A flowchart is a picture of the separate steps of a process in sequential order. It is a
generic tool that can be adapted for a wide variety of purposes, and can be used to
describe various processes, such as a manufacturing process, an administrative or
service process, or a project plan. Flowchart is often considered as a blueprint of a
design used for solving a specific problem.
Flowchart is Diagrammatic\Graphical representation of sequence of steps to solve
a problem.

Algorithm has the following characteristics


Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its
steps should be clear in all aspects and must lead to only one meaning.
Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs.
Well-Defined Outputs: The algorithm must clearly define what output will be
yielded and it should be well-defined as well.
Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops
or similar.
Feasible: The algorithm must be simple, generic and practical, such that it can be
executed upon will the available resources. It must not contain some future
technology, or anything.
Language Independent: The Algorithm designed must be language-independent,
i.e. it must be just plain instructions that can be implemented in any language, and
yet the output will be same, as expected.
The algorithm and flowchart include following three types of control structures.
1. Sequence(Process): In the sequence structure, statements are placed one after the
other and the execution takes place starting from up to down.
2. Branching (Selection): In branch control, there is a condition and according to a
condition, a decision of either TRUE or FALSE is achieved. In the case of TRUE, one
of the two branches is explored; but in the case of FALSE condition, the other
alternative is taken. Generally, the ‘IF-THEN’ is used to represent branch control.
3. Loop (Iteration/Repetition): The Loop or Repetition allows a statement(s) to be
executed repeatedly based on certain loop condition e.g. WHILE, FOR loops.
Advantages of Algorithms:
 It is a step-wise representation of a solution to a given problem, which makes it
SIVA SIVNI DEGREE COLLEGE 63 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
easy to understand.
 In Algorithm the problem is broken down into smaller pieces or steps hence, it is
easier for the programmer to convert it into an actual program.
 An algorithm uses a definite procedure.
 It is not dependent on any programming language, so it is easy to understand for
anyone even without programming knowledge.
 Every step in an algorithm has its own logical sequence so it is easy to debug.
Disadvantages of Algorithms:
 Writing an algorithm takes a long time so it is time-consuming.
 Branching and looping statements are difficult to show in Algorithms.
HOW TO DESIGN AN ALGORITHM?
In order to write an algorithm, following things are needed as a pre-requisite:
1. The problem that is to be solved by this algorithm.
2. The constraints of the problem that must be considered while solving the
problem.
3. The input to be taken to solve the problem.
4. The output to be expected when the problem the is solved.
5. The solution to this problem, in the given constraints.

HOW TO WRITE AN ALGORITHM


Step 1: Define your algorithms input: Many algorithms take in data to be processed,
e.g. to calculate the area of rectangle input may be the rectangle height and rectangle
width.
Step 2 :Define the variables: Algorithm's variables allow you to use it for more than
one place. We can define two variables for rectangle height and rectangle width as
HEIGHT and WIDTH (or H & W). We should use meaningful variable name e.g.
instead of using H & W use HEIGHT and WIDTH as variable name.
Step 3 :Outline the algorithm's operations: Use input variable for computation
purpose, e.g. to find area of rectangle multiply the HEIGHT and WIDTH variable
and store the value in new variable (say) AREA. An algorithm's operations can take
the form of multiple steps and even branch, depending on the value of the input
variables.
Step 4: Output the results of your algorithm's operations: In case of area of
rectangle output will be the value stored in variable AREA. if the input variables
described a rectangle with a HEIGHT of 2 and a WIDTH of 3, the algorithm would
output the value of 6.
What are Variables?
a program comprises of algorithm and data. Therefore, it is now necessary to
understand the concept of data. It is known that data is a symbolic representation
of value and that programs set the context that gives data a proper meaning.
In programs, data is transformed into information. The question is, how is data
represented in programs?
Almost Every algorithm contains data and usually the data is ‘contained’ in what is
called a variable. The variable is a container for a value that may vary during the
execution of the program.
For example, in the tea-making algorithm, the level of water in the kettle is a
variable, the temperature of the water is a variable, and the quantity of tea leaves is
also a variable.
Each variable in a program is given a name, for example,
 Water_Level
 Water_Temperature
SIVA SIVNI DEGREE COLLEGE 64 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
 Tea_Leaves_Quantity
Variables and data types
The data used in algorithms can be of different types. The simplest types of data
that an algorithm might use are
 numeric data, e.g., 12, 11.45, 901, etc.
 alphabetic or character data such as ‘A’, ‘Z’, or ‘This is alphabetic’
 logical data, that is, propositions with true/false values
NOTE: One should always try to choose meaningful names for variables in
algorithms to improve the readability of the algorithm or program. This is
particularly important in large and complex programs.
Developing algorithms using step-form
For illustrating the step-form the following conventions are assumed:
1. Each algorithm will be logically enclosed by two statements START and STOP.
2. To accept data from user, the INPUT or READ statements are to be used.
3. To display any user message or the content in a variable, PRINT statement will
be used. Note that the message will be enclosed within quotes.
4. There are several steps in an algorithm. Each step results in an action. The steps
are to be acted upon sequentially in the order they are arranged or directed.
FLOW CHART
 Flowchart is diagrammatic /Graphical representation of sequence of steps to solve
a problem.
Advantages of flowchart:
• Flowchart is an excellent way of communicating the logic of a program.
• Easy and efficient to analyze problem using flowchart.
• During program development cycle, the flowchart plays the role of a blueprint,
which makes program development process easier.
• After successful development of a program, it needs continuous timely
maintenance during the course of its operation. The flowchart makes program or
system maintenance easier.
• It is easy to convert the flowchart into any programming language code.
HOW TO DRAW A FLOWCHART?
The language used to write algorithm is simple and similar to day-to-day life
language. The variable names are used to store the values. The value store in
variable can change in the solution steps. In addition, some special symbols
(Operators in Programming Language) are used as below
Assignment Symbol (  or =) is used to assign value to the variable.
e.g., to assign value 5 to the variable HEIGHT, statement is
HEIGHT 5
or
HEIGHT = 5
The symbol ‘=’ is used in most of the programming language as an assignment
symbol, the same has been used in all the algorithms and flowcharts in the manual.
The statement C = A + B means that add the value stored in variable A and variable
B then assign/store the value in variable C.
The statement R = R + 1 means that add I to the value stored in variable R and then
assign/store the new value in variable R, in other words increase the value of
variable R by 1.

SIVA SIVNI DEGREE COLLEGE 65 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
To draw a flowchart following standard symbols are use

SIVA SIVNI DEGREE COLLEGE 66 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

GO TO statement also called unconditional transfer of control statement is used to


transfer control of execution to another step/statement.
e.g. the statement GOTO n will transfer control to step/statement n.

PSEUDO-CODE
The pseudo-code is a written form representation of the algorithm. However, it
differs from the step form as it uses a restricted vocabulary to define its action of
solving the problem. One problem with human language is that it can seem to be
imprecise. But the pseudo-code, which is in human language, tends toward more
precision by using a limited vocabulary.
It is one of the methods which can be used to represent an algorithm for a program.
It does not have a specific syntax like any of the programming languages and thus
cannot be executed on a computer.
Advantages of pseudocode:
 Pseudocode is easily written, read and understood
 Its implementation is very useful in structured design elements.
 It takes less time then drawing equivalent flowchart
 Converting it to programming code is much easier as compared to flowchart
 Can be easily modified when program’s logic needs modification
Disadvantages of Pseudocode:
 It is not visual
 Not suitable for design
 There is no standard format or style for writing, so one pseudocode may be
different from another.
 It is difficult to follow the logic and write pseudocode for a beginner and often
gets confused with an algorithm.

SIVA SIVNI DEGREE COLLEGE 67 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Roots of Quadratic Equation

Write an algorithm, flow chart and pseudo code


Begin
Number A,B,Sum
Input B1
Input B2
Sum=A+B
Output Sum
End

What Are The Strategies For Designing Algorithms


The strategies can be devised for designing algorithms.The following is a useful
strategy.
Investigation step
1. Identify the outputs needed.
This includes the form in which the outputs have to be presented. At the same time,
it has to be determined at what intervals and with what precision the output data
needs to be given to the user.
2. Identify the input variables available.
This activity considers the specific inputs available for this problem, the form in
which the input variables would be available, the availability of inputs at different
intervals, the ways in which the input would be fed to the transforming process.
3. Identify the major decisions and conditions.
This activity looks into the conditions imposed by the need identified and the
limitations of the environment in which the algorithm has to be implemented.

SIVA SIVNI DEGREE COLLEGE 68 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
4. Identify the processes required to transform inputs into required outputs.
This activity identifies the various types of procedures needed to manipulate the
inputs, within the bounding conditions and the limitations mentioned in step 3, to
produce the needed outputs.
5. Identify the environment available.
This activity determines the kind of users and the type of computing machines and
software available for implementing the solution through the processes considered
in steps.
Top–down development step
1. Devise the overall problem solution by identifying the major components of the system.
The goal is to divide the problem solution into manageable small pieces that can be
solved separately.
2. Verify the feasibility of breaking up the overall problem solution.
The basic idea here is to check that though each small piece of solution procedure are
independent, they are not entirely independent of each other, as they together form
the whole solution to the problem. In fact, the different pieces of solution procedures
have to cooperate and communicate in order to solve the larger problem.
Stepwise refinement
1. Work out each and every detail for each small piece of manageable solution procedure.
very input and output dealt with and the transformation algorithms implemented in
each small piece of solution procedure, which is also known as process, is detailed.
Even the interfacing details between each small procedure are worked out.
2. Decompose any solution procedure into further smaller pieces and iterate until the desired
level of detail is achieved.
E very small piece of solution procedure detailed in step 1 is checked once again. If
necessary any of these may be further broken up into still smaller pieces of solution
procedure till it can no more be divided into meaningful procedure.
3. Group processes together which have some commonality. Some small processes may
have to interface with a common upper level process. Such processes may be grouped
together if required.
4. Group variables together which have some appropriate commonality.
Certain variables of same type may be dealt as elements of a group.
5. Test each small procedure for its detail and correctness and its interfacing with the other
small procedures.
Walk through each of the small procedures to determine whether it satisfies the
primary requirements and would deliver the appropriate outputs. Also, suitable
tests have to be carried out to verify the interfacing between various procedures.
Explain About Structured Programming Concept
A better way of programming—a systematic way to organize programs—called
structured programming.
Structured programming has been called a revolution in programming and is
considered as one of the most important advancements in software in the past two
decades.
Structured programming is:
concerned with improving the programming process through better organization of
programs and better programming notation to facilitate correct and clear escription
of data and control structure.
concerned with improved programming languages and organized programming
techniques which should be understandable and therefore, more easily modifiable
and suitable for documentation.

SIVA SIVNI DEGREE COLLEGE 69 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
More economical to run because good organization and notation make it easier for
an optimizing compiler to understand the program logic.
more correct and therefore more easily debugged, because general correctness
theorems dealing with structures can be applied to prove the correctness of
programs.
Structured programming can be defined as a
 top–down analysis for program solving
 modularization for program structure and organization
 structured code for individual modules
Top-down analysis is a general method for attending to any problem. It provides a
strategy that has to be followed for solving all problems.
The four basic steps to top-down analysis are as follows:
Step 1: Define the complete scope of the problem to determinethe basic requirement
for its solution. Three factorsmust be considered in the definition of a programming
problem.
Input What data is required to be processed by the program?
Process What must be done with the input data? What typeof processing is required?
Output What information should the program produce? Inwhat form should it be
presented?
Step 2: Based on the definition of the problem, divide theproblem into two or more
separate parts.
Step 3: Carefully define the scope of each of these separatetasks and subdivide them
further, if necessary, into two ormore smaller tasks.
Step 4: R epeat step 3. Every step at the lowest level describesa simple task, which
cannot be broken further.
Modular programming is a program that is divided into logically independent
smaller sections, which can be written separately.
These sections, being separate and independent units, are called modules.
A module consists of a series of program instructions or statements in some
programming language.
A module is clearly terminated by some special markers required by the syntax of
the language. For example, a BASIC language subroutine is terminated by the return
statement.
A module as a whole has a unique name.
A module has only one entry point to which control is transferred from the outside
and only one exit point from which control is returned to the calling module.
Structured Code:
Structured programming is a method of coding, i.e., writing a program that produces
awell-organized module.
A high-level language supports several control statements,also called structured
control statements or structured code,to produce a well-organized structured
module. These control
statements represent conditional and repetitive type of executions.
Each programming language has different syntax forthese statements.

SIVA SIVNI DEGREE COLLEGE 70 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
BASICS OF C
Write about Brief History of C
C language is a general purpose and structured programming language developed
by 'Dennis Ritchie' at AT &T's Bell Laboratories in the year 1972 in USA. It is also
called as 'Structured oriented programming language.'
 The C programming language is a structure oriented programming language,
developed at Bell Laboratories in 1972 by Dennis Ritchie.
 C programming language features were derived from an earlier language called
“B” (Basic Combined Programming Language – BCPL)
 C language was invented for implementing UNIX operating system.
 In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C
Programming Language” and is commonly known as K&R C.
 In 1983, the American National Standards Institute (ANSI) established a
committee to provide a modern, comprehensive definition of C. The resulting
definition, the ANSI standard, or “ANSI C”, was completed late 1988.
 Many of C’s ideas & principles were derived from the earlier language B, thereby
naming this new language “C”.
Language Year Developed Description
Name
ALGOL is an acronym for
Cambridge Algorithmic Language. It was the
ALGOL-60 University first structured procedural
1960 programming language,
developed in the late 1950s and
once widely used in Europe. But
it was too abstract and too
general
Structured language.

CPL Cambridge CPL is an acronym for Combined


(Combined 1963 University Programming Language. It was
Programming developed atCambridge
Language) University.

BCPL Martin Richard BCPL is an acronym for Basic


(Basic Combined at Cambridge Combined
1967 University Programming Language. Itwas
Programming
Language) developed by Martin Richards at
Cambridge University in
1967. BCPL was not so powerful.
So, it wasfailed.

Ken Thompson B language was developed by


B atAT &T's Bell Ken Thompsonat AT & T Bell
1970 Laboratories in 1970. It was
Laboratories.
machine dependent. So, it leads
to specific problems.

SIVA SIVNI DEGREE COLLEGE 71 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

'C' Programming Language was


Dennis.M developed by Dennis Ritchie at
1972 Ritchie atAT&T' AT & T Bell Laboratories in1972.
C
Bell Laboratory. This is general purpose,
compiled, structured
programming language.
Dennis Ritchie studied the BCPL,
then improved and named it as
'C' which is thesecond letter of
BCPL

WHY IS C POPULAR
 It is reliable, simple and easy to use.
 C is a small, block-structured programming language.
 C is a portable language, which means that C programs written on one system can
be run on other systems with little or no modification.
 C has one of the largest assortments of operators, such as those used for
calculations and data comparisons.
 Although the programmer has more freedom with data storage, the languages do
not check data type accuracy for the programmer.
WHY TO STUDY C
 By the early 1980s, C was already a dominant language in the minicomputer
world of Unix systems. Since then, it has spread to personal computers
(microcomputers) and to mainframes.
 Many software houses use C as the preferred language for producing word
processing programs, spreadsheets, compilers, and other products.
 C is an extremely flexible language—particularly if it is to be used to write
operating systems.
C is a Structures programming language which consists of a set of functions and
operators that can be used to write any complex programs. C is a highly portable
language and is so popular especially among software developers, whose
application have to run on any different platforms.
C is a platform dependent language.

SIVA SIVNI DEGREE COLLEGE 72 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
As we know programming languages are divided into 2 categories
1. Machine oriented: which are designed to give better machine efficiency i.e. faster
program execution.
2. Problem oriented: which are designed to give better program efficiency i.e. faster
program development.
A C-language stand between these categories that’s why is called middle level
language,developed for both relatively good machine efficiency and program
efficiency.C allows you to develop multiple source program files that are
independently compiled and executed. C is a case sensitive, reliable and easy to use.
WRITE ABOUT FEATURES AND CHARACTERISTICS OF C LANGUAGE:
Accuracy: C is a robust language this refers to the state of being accurate of the
calculations
Portability: C is portable language where the code transfer from one machine to
another machine and executed.
Flexibility: A program to be as general as possible within the readable limit.
We will write more than one instruction in one statement
Effectiveness (Integrity): it consists of more than one statement grouped together
assingle unit and executed.
Efficiency: this involves efficient execution speed and memory utilization of program
Simple: C is a simple language in the sense that it provides a structured approach,
the rich set of libraryFunctions, data types, etc.
Reliability: it should be clear that all program elements would be meaningless, if
the calculations are not carried out correctly.
Interactivity (Modularity): program can be divided into a series of subtasks known
as modules. These subtasks are re arranged according to program called functions.
Memory Management: It supports the feature of dynamic memory allocation. In C
language, we can free theallocated memory at any time by calling the free() function.
Pointer: C provides the feature of pointers. We can directly interact with the
memory by usingthe pointers. We can use pointers for memory, structures, functions,
array.
Recursion: In C, we can call the function within the function. It provides code
reusability for every function. Recursion enables us to use the approach of
backtracking.
DEVELOPING PROGRAMS IN C
Write Typical Steps For Entering, Compiling, And Executing C Programs
There are mainly three steps in developing a program in C:
1. Writing the C program
2. Compiling the program
3. E xecuting the program

SIVA SIVNI DEGREE COLLEGE 73 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 Creating a program: Aneditor like notepad or WordPad or OR IDE O R turboc
editor is used to create a C program. This file contains a source code which consists
of executable code. The file should be saved as '*.c' extension only.
 Compiling the program: The next step is to compile the program. The code is
compiled by using compiler. Compiler converts executable code to binary code i.e.
object code. Compiling involves preprocessing, compilation, assembly,and linking.
Preprocessing It is the first phase of C compilation. It processes include-files,
conditional compilation instructions,and macros. The C preprocessor is used to
modify the program according to the preprocessor directives in the source code.
A preprocessor directive is a statement (such as #define) that gives the preprocessor
specific instructions on how to modify
the source code. The preprocessor is invoked as the first part of the compiler
program’s compilation step. It is usually hidden from the programmer because it is
run automatically by the compiler.
 Compilation It is the second step of the compiling process.It takes the output of the
preprocessor and the source code, and generates assembler source code. The
compiler examines each program statement contained in the source program and
checks it to ensure that it conforms to the syntax and semantics of the language. If
mistakes are discovered by the compiler during this phase, they are reported to the
user. The errors then have to be corrected in the source program (with the use of an
editor), and the program has to be recompiled.
 Assembly It is the third stage of compilation. It takes the assembly source code and
produces an assembly listing with offsets. The assembler output is stored in an
object file. After the program has been translated into an equivalent assembly
language program, the next step in the compilation process is to translate the
assembly language statements into actual machine instructions.
 Linking It is the final stage of compilation. After the program has been translated
into object code, it is ready to be linked. The purpose of the linking phase is to get
the program into a final form for execution on the computer. The functions are the
part of the standard C library, provided by every C compiler. The program may use
other source programs that were previously processed by the compiler. These
functions are stored as separate object files which must be linked to the object file.
Linker handles this linking.
The process of compiling and linking a program is often called building. The final
linked file, which is in an executable object code format, is stored in another file on
the system ready to be run or executed.
 Linking a program to library: The object code of a program islinked with libraries
that are needed for execution of a program. The linker is used to link the program
with libraries. It creates a file with '*.exe' extension.
 Execution of program: The final executable file is then run by dos command
prompt or by any othersoftware.
When the program is executed, each of the statements of the program is sequentially
executed. If the program requests any data from the user, known as input, the
program temporarily suspends its execution so that the input can be entered. Or,
the program might simply wait for an event, such as a mouse being clicked, to occur.
Results that are displayed by the program, known as output, appear in a window,
sometimes called the console. Or, the output might be directly written to a file on
the system.

SIVA SIVNI DEGREE COLLEGE 74 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

FILES USED IN A C PROGRAM


Source File- This file contains the source code of the program. The file extension
of any c file is .c. The file contains C source code that defines the main function &
maybe other functions.
Header File- A header file is a file with extension .h which contains the C function
declarations and macro definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension .o,
meaning relocatable format machine code that is usually not directly executable.
Object files are produced by an assembler, compiler, or other language translator,
and used as input to the linker, which in turn typically generates an executable or
library by combining parts of object files.
Executable File- The binary executable file is generated by the linker. The linker
links the various object files to produce a binary file that can be directly executed.
USES OF C
The C programming language is used for developing system applications that forms a
major portion of operating systems such as Windows, UNIX and Linux. Below are
some examples of C being used:
 Database systems
 Graphics packages
 Word processors
 Spreadsheets
 Operating system development
 Compilers and Assemblers
 Network drivers
 Interpreters
DEFINE ERROR AND WHAT ARE THE TYPES OF ERRORS IN C
Errors are the problems or the faults that occur in the program, which makes the
behavior of the program abnormal, and experienced developers can also make these
faults. Programming errors are also known as the bugs or faults, and the process of
removing these bugs is known as debugging.
These errors are detected either during the time of compilation or execution. Thus,
the errors must be removed from the program for the successful execution of the
program.

SIVA SIVNI DEGREE COLLEGE 75 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
There are mainly five types of errors exist in C programming:
o Syntax error
o Run-time error
o Linker error
o Logical error
o Semantic error
Compilation (syntax ) errors:
Syntax errors are also known as the compilation errors as they occurred at the
compilation time, or we can say that the syntax errors are thrown by the compilers.
These errors are mainly occurred due to the mistakes while typing or do not follow
the syntax of the specified programming language. These mistakes are generally
made by beginners only because they are new to the language. These errors can be
easily debugged or corrected.
For example:
1. If we want to declare the variable of type integer,
2. int a; // this is the correct form
3. Int a; // this is an incorrect form.
these are raised when we compile the program and can be located and
corrected easily. Most common compilation or syntax errors are.
· Undefined variable
· Redeclaration of variable
· Unterminated string character
· Missing semicolon ;
· Function call missing ( ,;”)
· Function should have prototype.
Run-time error
Sometimes the errors exist during the execution-time even after the successful
compilation known as run-time errors. When the program is running, and it is not
able to perform the operation is the main cause of the run-time error.
The division by zero is the common example of the run-time error. These errors are
very difficult to find, as the compiler does not point to these errors.
Linker errors are mainly generated when the executable file of the program is not
created. This can be happened either due to the wrong function prototyping or usage
of the wrong header file. For example, the main.c file contains the sub() function
whose declaration and definition is done in some other file such as func.c.
During the compilation, the compiler finds the sub() function in func.c file, so it
generates two object files, i.e., main.o and func.o. At the execution time, if the
definition of sub() function is not found in the func.o file, then the linker error will
be thrown. The most common linker error that occurs is that we use Main() instead
of main().
Logical error
The logical error is an error that leads to an undesired output. These errors produce
the incorrect output, but they are error-free, known as logical errors. These types of
mistakes are mainly done by beginners. The occurrence of these errors mainly
depends upon the logical thinking of the developer. If the programmers sound
logically good, then there will be fewer chances of these errors.
Semantic error : Semantic errors are the errors that occurred when the statements
are not understandable by the compiler.

SIVA SIVNI DEGREE COLLEGE 76 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
The following can be the cases for the semantic error:
o Use of a un-initialized variable.
int i; i=i+2;
o Type compatibility
int b = "Saiprasad v";
o Errors in expressions
int a, b, c; a+b = c;
o Array index out of bound
int a[10]; a[10] = 34;
The following are the Steps to work on c program:
1. To write a new program selects ―New command from ―File menu.
2. To save the working program select ― Save command from ― File menu or press F2
and select the location where we want to save and enter the file name with extension
― .c
3. To compile the program select ― Compile to OBJ command from ―compile menu
or press Alt + F9. Then it shows the list of errors or warnings. If the program is error-
free then the compiler creates an object file (.OBJ) and an executable file (.EXE).
4. To execute the program select ―Run command from ―Run menu or press Ctrl + F9.
5. To see the output of the execution select ―User Screen command from ―Run menu
or press Alt + F5.
6. To close the editor selects „Quit‟ command from ―File‖ menu or press Alt + X.
7. Then type exit to exit from command prompt
How to install C
There are many compilers available for c and c++. You need to download any one.
Here, we are going to use Turbo C++. It will work for both C and C++. To install the
Turbo C software, you need to follow following steps.
1. Download Turbo C++, Create turboc directory inside c drive and extract the tc3.zip
inside c:\turboc
2. Double click on install.exe file
3. Click on the tc application file located inside c:\TC\BIN to write the c program
A SIMPLE C STRUCTURE PROGRAM
Documentation Section
Links Section (File inclusion section)
Definition Section
Global variable declaration Section
main (void)
{
Local Variable declaration ; or Function declaration();

Executable statements;
}
Sub Function definition (arguments)
{
Local variable declaration;
Executable Statements;
}

SIVA SIVNI DEGREE COLLEGE 77 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Documentation Section: This section used to provide the information about which
program we are writing and purpose of program. It consists of set of comment lines
whichinclude name of a program, author name, creation date and other information.
Comments: Comment line is used for increasing the readability of the
program. It is useful in explaining the program and generally used for
documentation. It is enclosed within the delimiters. Comment line can be single
or multiple lines but should not be nested. It can be anywhere in the program.
There are two types of comments in C.
Single Line Comments: Single line comments are defined using two backward
slashes(//)
EX: // program to display name
Multiline Comments: Multiline comments are defined using a pair of /*
text…
....................................................................................................................................................
*/.
EX: /* this program takes two values into two variable and calculates its sum */
These statements can be put anywhere in the program.The compiler considers these
as non-executable statements.
Linkage Section (Header File Section): It is used to link the required system libraries
or header files to our program. All header files having pre-defined functionality of
keywords, pre-defined functions. We use the keyword include and symbol „ # ‟ to
write linkage section.
Syntax: # include <headerfilename.h> or # include ―headerfilename.h‖
Ex: #include<stdio.h> or #include ―stdio.h‖
Definition Section:
It is used to declare global or public variable. To use any variable it must be declared
with its data type before the first executable statement. The variables which declared
in a block are available in that block only. To use the variable in the entire program
with same effect it must be declared as global.
It is used to define symbolic constants or set values to variables. And also used to
define macros.
Ex: #define MAX 10
Global Declaration Section: This section is used to declare variables and functions
before main program/function or outside of any function. The variable declared in
this section act asa global or public variable. These variables can be used in the entire
program with same effect.
Main Program Section : Every C program contains a function called main. This is
the starting point of the program. A C program may contain one or more functions
one of which must be main(). Functions are the building blocks of a C program.
For now, the functions may be recognized by the presence of parentheses after their
names. When a C program is executed, main() is where the action starts. Then, other
functions maybe ‘invoked’ or called.It includes two parts as declaration part and
executable part.
 Variable declaration section: Used to declare private variable.
 Function declaration section: Used to declare functions of program from
which we get required output.
 Then, executable statements are placed for execution.
Sub Function definition: This section used to define a sub task or sub program to
solve a particular task or problem declared in the function defination.

SIVA SIVNI DEGREE COLLEGE 78 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
NOTE:
C uses a semicolon as a statement terminator; the semicolon is required as a signal
to the compiler to indicate that a statement is complete.
All program instructions, which are also called statements, have to be written in
lower-case characters.
Declaration means describing the type of a data object to the compiler but not
allocating any space for it.
Definition means declaration of a data object and also allocating space to hold the
data object.

ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the
language.
Character Set : Communicating with a computer involves speaking the language the
computer understands. In C, various characters have been given to communicate.

SIVA SIVNI DEGREE COLLEGE 79 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Character set in C consists of;
Types Character Set
Lower case a-z
Upper case A-Z
Digits 0-9
Special Character !@#$%^&*
White space Tab or new lines or space
Expalin Tokens in C
Tokens are the basic lexical building blocks of source code. In other words, tokens are
one or more symbols understood by the compiler that help it interpret the program
code. Characters are combined into tokens according to the rules of the programming
language. The compiler checks the tokens so that they can be formed into legal strings
according to the syntax of the language.
There are five classes of tokens: identifiers, keywords, operators, separators, and
constants.
Identifier It is a sequence of characters invented by the programmer to identify or
name a specific object, and the name is formed by a sequence of letters, digits, and
underscores.
Ex: name,rollno,marks
Keywords These are explicitly reserved words that have a strict meaning as
individual tokens to the compiler. They cannot be redefined or used in other
contexts. Use of variable names with the same name as any of the keywords will
cause a compiler error.
Ex: for,do,if,else,break
Operators: operator is a symbol. These are tokens used to indicate an action to be
taken (usually arithmetic operations, logical operations, bit operations, and
assignment operations). Operators can be simple operators (a single character token)
or compound operators (two or more character tokens).
Ex: +,*,&,>

Separators These are tokens used to separate other tokens.


Two common kinds of separators are indicators of an end of an instruction(;) and
separators used for grouping({ }).
Constant It is an entity that does not change. A constant is an explicit data value
written by the programmer.

SIVA SIVNI DEGREE COLLEGE 80 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Thus, it is a value known to the compiler at compiling time. The compiler may deal
with this value in any of several ways, depending on the type of constant and its
context.
For example, the binary equivalent of the constant may be inserted directly into the
output code stream. The value of the constant may be stored in a special data area in
memory. The compiler may decide to use the constant’s value for its own immediate
purpose, e.g., to determine how much storage it should allocate to a data array. C
permits integer constants, floating-point constants, character constants, and string
constants.
Consider the following piece of code for example of tokens
if(x<5)
x = x + 2;
else
x = x + 10.5;
Here, the tokens that will be generated are
Keywords : if , else,for,do
Identifier : x,rollno
Constants : 2, 10.5
Operators : +,=,++,--,>,<,
Separator : ;,,
 Define Identifier
Identifier or name is a sequence of characters created by the programmer to identify
or name a specific object. In C, variables, arrays, functions, and labels are named.
Describing them may help to learn something about the character of the language
since they are elements that C permits the programmer to define and manipulate.
Some rules must be kept in mind when naming identifiers.
These are stated as follows:
1. The first character must be an alphabetic character (lower-case or capital letters) or
an underscore ‘_’.
2. All characters must be alphabetic characters, digits, or underscores.
3. The first 31 characters of the identifier are significant. Identifiers that share the
same first 31 characters may be indistinguishable from each other.
4. A keyword cannot be duplicated by an identifier. A keyword is word which has
special meaning in C.
Some examples of proper identifiers are employee_number, box_4_weight,
monthly_pay, interest_per_annum, job_number,
and tool_4.
Some examples of incorrect identifiers are 230_item,
#pulse_rate, total~amount, /profit margin, and ~cost_per_item.
 Define Keywords
Keywords are the vocabulary of C. Because they are special to C, one cannot use them
for variable names. There are 32 words defined as keywords in C. These have
predefined uses and cannot be used for any other purpose in a C program.
A keyword is word which has special meaning in C. They are used by the compiler
to compile the program. They are always written in lowercase letters. A complete list
of these keywords is

SIVA SIVNI DEGREE COLLEGE 81 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

EXPLAIN THE CONCEPT OF CONSTANTS IN C:


A constant is an entity that doesn't change during the execution of a program. A
constant is an explicit data value written by the programmer

There are 4 basic types of constants.


They are
 integer constants
 floating-point constants
 character constants and string
constants
1. Real Constant: (floating point
constants) It is a decimal number (i.e.:
base 10) with a decimal point or an
exponent or both. Real constants are
often called Floating Point constants.
The real constants could be written in
two forms—Fractional form and
Exponential form.
These numbers have greater range than integer constants.
Rules for constructing real constants expressed in fractional form:
a) A real constant must have at least one digit.
b) It must have a decimal point.
c) It could be either positive or negative.
d) Default sign is positive.
e) No commas or blanks are allowed within a real constant.
Ex. +325.34, 426.0, -32.76, -48.5792
Rules for constructing real constants expressed in exponential form:
a) The mantissa part and the exponential part should be separated by a letter e.
b) The mantissa part may have a positive or negative sign.
c) Default sign of mantissa part is positive.
d) The exponent must have at least one digit, which must be a positive or negative
integer. Default sign is positive.
e) Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.
Ex. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5

SIVA SIVNI DEGREE COLLEGE 82 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
2. Integer Constant: An integer constant consists of a sequence of digits. It is normally
interpreted as a decimal value.
Thus, 1, 25, and 23456 are all decimal integer constants. Literal integers can be
expressed in decimal, octal, and hexadecimal notations
92 /* decimal */
0134 /* equivalent octal */
0x5C /* equivalent hexadecimal */
A literal integer (e.g., 1984) is always assumed to be of type int, unless it has an ‘L’
or ‘l’ suffix, in which case it is treated as a long. Also, a literal integer can be
specified to be unsigned using the suffix U or u.
For example, 1984L 1984l 1984U 1984u 1984LU 1984ul
 It must have at least one digit.
 It should not contain a decimal place.
 It can be positive or negative.
 Use of blank space and comma is not allowed between real constants.
Example: 1990, 194, -394
3. Character Constant: A character constant normally consists of a single character
enclosed in single quotes. Thus, for example, ‘b’ and ‘$’ are both character constants.
Each takes on the numeric value of its character in the machine’s character set. Unless
stated otherwise, it will henceforth be assumed that the ASCII code is used. This table
is provided in Appendix B. Thus, for example, writing down the character constant
‘A’ is equivalent to writing down the hex value 41 or the octal value 101.
It is a single alphabet or a digit or a special symbol enclosed in a single quote.
Maximum length of a character constant is 1.
Example: 'T', '9', '$'
4. String Constant: it consists of any number of consecutive characters enclosed in
double quotes.
A string constant is a sequence of characters enclosed in double quotes. Whenever
the C compiler encounters a string constant, it stores the character sequence in an
available data area in memory. It also records the address of the first character and
appends to the stored sequence an additional character, the null character ‘\0’, to
mark the end of the string
 It is collection of characters enclosed in double quotes.
 It may contain letters, digits, special characters and blank space.
Example: "Technology Web Solutions", “C program”, “mathematics” etc……
Note: A common programming error results from confusing a single-character string
(e.g., “A”) with a single character (e.g., ‘A’).
These two are not equivalent. The former consists of two bytes (the character ‘A’
followed by the character ‘\0’), whereas the latter consists of a single byte.

SIVA SIVNI DEGREE COLLEGE 83 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

WRITE ABOUT SYMBOLIC CONSTANTS


A symbolic constant is a name that substitutes for a sequence of characters, which
represent a numeric, character or string constant. A symbolic constant is defined in
the beginning of a program by using #define, without: at the end.
Example: #define pi 3.1459
#define INTEREST P*N*R/100
With this definition it is a program the values of p, n, r are assigned the value of
INTEREST is computed.
Note: symbolic constants are not necessary in a C program.

Explain In Detailed About VARIABLE


 It is a data name in which data is used to store and may change during program execution.
It is opposite to constant. Variable name is a name given to memory cells in location of a
computer where data is stored. (OR)
 An entity that may vary during program execution is called a variable. Variable names
are names given to locations in memory. Variable name can be chosen by programmer
in a meaningful way so as to reflect its nature in the program. (Or)
 Variables are names that are used to store values. It can take different values but one at a
time. A data type is associated with each variable & it decides what values the variable can
take. When you decide your program needs another variable, you simply declare (or define)
a new variable.
All variables have three important attributes.
 A data type that is established when the variable is defined,
 e.g., integer, real, character. Once defined, the type of a C variable cannot be
changed.
 The name of the variable.
 A value that can be changed by assigning a new value to the variable.
Declaration of a variable: Defining a variable means the compiler has to now assign
storage to the variable because it will be used in the program.
A variable should be declared with its data type before using it.
Syntax: datatype var1, var2…..; Example: int a,b;

Assigning a value to a variable:


Syntax: datatype var=value; or datatype var1=var2; datatype var=expression;
Example int a=10;
int b-=a;
int c=a+b;

SIVA SIVNI DEGREE COLLEGE 84 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Initialization of Variables
When a variable is declared, it contains undefined value commonly known as
garbage value. If we want we can assign some initial value to the variables during
the declaration itself. This is called initialization of the variable.
int pageno=10;
char grade=’A’;
float salary= 20000.50;
It can be:
 char: Can hold/store a character in it.
 int: Used to hold an integer.
 float: Used to hold a float value.
 double: Used to hold a double value.
Rules for variables:
 First character should be letter or alphabet.
 Keywords are not allowed to use as a variable name.
 White space is not allowed.Only underscore, special symbol is allowed between two
characters.
 C is case sensitive i.e. UPPER and lower case are significant.
 The length of identifier may be up to 31 characters but only the first 8 characters are
significant by compiler.
DIFFERENCES BETWEEN LOCAL AND GLOBAL VARIABLES
 A variable can be either of global or local scope. A global variable is a variable
declared in the main body of the source code, outside all functions, while a local
variable is one declared within the body of a function or a block.
 Global variables can be referred from anywhere in the code, even inside functions,
whenever it is after its declaration.
 The scope of local variables is limited to the block enclosed in braces ({}) where they
are declared.
EXPLAIN ABOUT DATA TYPES IN C:
"Data type can be defined as the type of data or constant stored in the memory. "When we
use a variable in a program then we have to mention the type of data. This can be handled
using data type in C.
Data types specify how we enter data into our programs and what type of data we
enter. C language has some predefined set of data types to handle various kinds of
data that we can use in our program. These data types have different storage
capacities.
C language supports different type of data types:
1. Primary data types: These are fundamental data types in C namely integer (int),
floating point (float), character (char) ,double and void.
2. Derived data types: Derived data types are nothing but primary data types but a
little twisted or grouped together like array,function.
3. User Defined data type: these are defined by user as per the operation required to
perform on a specific area. Like structure, union enum,typedef
4. Empty data type: valueless—Keyword used is void (The void type specifies an empty
set of values.It is used as the type returned by functions that generate no value.)
5. Pointer data type: pointer- A pointer is a variable that stores the memory address of an
object. The pointer then simply “points” to the object. The type of the object must
correspond with the type of the pointer. Pointers are used extensively in both C and C++
for three main purposes:
 To allocate new objects on the heap.
 To pass functions to other functions.
 To iterate over elements in arrays or other data structures.

SIVA SIVNI DEGREE COLLEGE 85 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Data type determines the type of data a variable will hold. If a variable x is declared
as int. it means x can hold only integer values. Every variable which is used in the
program must be declared as what data-type it is. The type of a variable determines
how much space it occupies in storage and how the bit pattern stored is interpreted
Primitive data types
C provides a standard, minimal set of basic data types.Sometimes these are called
‘primitive’ types. More complex data types can be built up from these basic types. C
has five basic data types and they are as follows:
 character—Keyword used is char
 integer—Keyword used is int
 floating-point—Keyword used is float
 double precision floating point—Keyword used is double

Keyword Format Specifier Size Data Range


(data type)

char %c 1Byte(8 Bits) -128 to +127

unsigned char <-- -- > 8 Bytes 0 to 255

int %d 2 Bytes -32768 to +32767

long int %ld 4 Bytes -231 to +231

unsigned int %u 2 Bytes 0 to 65535

float %f 4 Bytes -3.4e38 to +3.4e38

double %lf 8 Bytes -1.7e38 to +1.7e38

long double %lf 12-16 Bytes -3.4e38 to +3.4e38

SIVA SIVNI DEGREE COLLEGE 86 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Integer type: keyword int used to represent integer data type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:
Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Floating point type: keyword float used to represent integer data type
Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
Float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
Character type: keyword char used to represent integer data type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
void type: void type means no value. This is usually used to specify the type of
functions which returns nothing.
QUALIFIER:
When qualifier is applied to the data type then it changes its size.
The specifiers and qualifiers for the data types can be broadly classified into three
types:
 Size specifiers—short and long
 Sign specifiers—signed and unsigned
 Type qualifiers—const, volatile, and restrict
Conversion Characters (format specifies):
Conversion characters or format specifiers are used to provide the format for the
value to be print.. It has a prefix ‘% ‘and followed by a specifier.
%d : prints integer
%f : prints float and double
%c : prints character
%s : prints string
%o : prints octal value
%u : prints unsigned integer
%x : prints hexa decimal value

SIVA SIVNI DEGREE COLLEGE 87 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Define and list out different types of operators
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. There are three types of arithmetic operators in C: binary, unary,
and ternary.
Unary Operators :
The unary operator works on a single operand or variable. Increment/Decrement
operators also called as Unary operators.
Binary Operators:
The binary operator works on two operands or variables like arithmetic operator,
relational operator, bit-wise operator assignment operator, and logical operator.
Ternary Operator:
The ternary operator works on more than two operands or variables like
conditional operator. The conditional operator also called a ternary operator.

C language is rich in built-in operators and provides the following types of operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Increment and decrement operators
• Conditional operators
• Misc Operators
Unary operators
The unary ‘–’ operator negates the value of its operand (clearly, a signed number).
Unary increment and decrement operators The unary ‘++’ and ‘--’ operators,
respectively, increment or decrementthe value of a variable by 1.
There are ‘pre’ and ‘post’ variants for both operators that do slightly different things
asexplained below.
var++ increment ‘post’ variant var-- decrement ‘post’variant
++var increment ‘pre’ variant --var decrement ‘pre’variant
Basic rules for using ++ and – – operators
The operand must be a variable but not a constant or an expression.
The operator ++ and -- may precede or succeed the operand.

SIVA SIVNI DEGREE COLLEGE 88 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Pre- and post-variations of ++ and – – operators The pre and post- (++ and --) operators
differ in the value used for the operand n when it is embedded inside expressions.

Binary operators
Arithmetic operator:
These are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.

SIVA SIVNI DEGREE COLLEGE 89 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
C provides five basic arithmetic binary operators.

Relational Operators:
These operators are used to compare the value of two variables. Following table
shows all the relational operators supported by C language. Assume variable A
holds 10 and variable B holds 20, then:

Logical Operators:
These operators are used to perform logical operations on the given two variables.
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then:

Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Bitwise operators
are used in bit level programming. These operators can operate upon int and char
but not on float and double.
Showbits( ) function can be used to display the binary representation of any integer
or character value.
SIVA SIVNI DEGREE COLLEGE 90 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Bit wise operators in C language are; &(bitwise AND), | (bitwise OR), ~ (bitwise
OR), ^ (XOR), << (left shift) and >> (right shift).

The Bitwise operators supported by C language are explained in the following


table. Assume variable A holds 60 (00111100) and variable B holds 13 (00001101),
then:

Ternery operators:
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes
different statements according to test condition whether it is either true or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is returned
and if false expression2 is returned.
Let us understand this with the help of a few examples:
int x, y ;
scanf ( “%d”, &x ) ;
y = ( x> 5 ? 3 : 4 ) ;
This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.
Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.
There are following assignment operators supported by C language:

SIVA SIVNI DEGREE COLLEGE 91 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Misc Operators:
There are few other operators supported by c language.

Misc operators
Comma Operator
The comma operator allows the evaluation of multiple expressions, separated by the
comma, from left to right in order and the evaluated value of the rightmost xpression
is accepted as the final result. The general form of an expression
using a comma operator is
expressionM = (expression1, expression2, …,expressionN);
where the expressions are evaluated strictly from left to right and their values
discarded, except for the last one, whose type and value determine the result of the
overall expression

SIVA SIVNI DEGREE COLLEGE 92 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

sizeof Operator
C provides a useful operator, sizeof, for calculating the size of any data item or type.
It takes a single operand that may be a type name (e.g., int) or an expression (e.g.,
100) and returns the size of the specified entity in bytes. The outcome is totally
machine-dependent. The following program illustrates the use of sizeof on the built-
in types we have encountered so far.
int main()
{
printf(“char size = %d bytes\n”, sizeof(char));
printf(“short size = %d bytes\n”, sizeof(short));
printf(“int size = %d bytes\n”, sizeof(int));
printf(“long size = %d bytes\n”, sizeof(long));
printf(“float size = %d bytes\n”, sizeof(float));
printf(“double size = %d bytes\n”, sizeof(double));
printf(“1.55 size = %d bytes\n”, sizeof(1.55));
printf(“1.55L size = %d bytes\n”, sizeof(1.55L));
printf(“HELLO size = %d bytes\n”, sizeof(“HELLO”));
return 0;
}
Define Expression And Types Of It
An expression is nothing but a valid combination of constants, variables and
operators.
An expression consists of a combination of operators, operands, variables & function
calls.
An expression can be arithmetic, logical or relational.
This consists of a single entity like a constant, a variable, an array or a function name. it
also consists of some combinations of such entities interconnected by operators.
Example: a, a+b, x=y, c=a+b, x<=y etc……..
There are four types of expressions exist in C:
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of a particular expression produces a specific value.
For example:
x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal
is an expression.
SIVA SIVNI DEGREE COLLEGE 93 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic
operators. An arithmetic expression computes a value of type int, float or double.
An example.
6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)
Relational Expressions
 A relational expression is an expression used to compare two operands.
 It is a condition which is used to decide whether the action should be taken or
not.
 In relational expressions, a numeric value cannot be compared with the string
value.
 The result of the relational expression can be either zero or non-zero value.
Here, the zero value is equivalent to a false and non-zero value is equivalent to
true.
Ex: a>=9 It is used to check whether the value of a is greater than or
equal to 9.
Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero
value.
o It is a complex test condition to take a decision.
Ex: ( x > 4 ) && ( x < 6 ) It is a test condition to check whether the x is greater
than 4 and x is less than 6. The result of the condition is true only when both the
conditions are true.
Conditional Expressions
A conditional expression is an expression that returns 1 if the condition is true
otherwise 0.
A conditional operator is also known as a ternary operator.
The Syntax of Conditional operator
Suppose exp1, exp2 and exp3 are three expressions.
exp1 ? exp2 : exp3
status = (age>18) ? “eligible”: “not eligabl”;

DEFINE STATEMENTS AND EXPLAIN TYPES OF IT


Statements are the primary building blocks of a program. A program is a series of
statements with some necessary punctuation. A statement is a complete instruction
to the computer. In C, statements are indicated by a semicolon at the end.
Therefore
legs = 4 is just an expression (which could be part of a larger expression), but
legs = 4;
is a statement.
Statements are the ``steps'' of a program. Most statements compute and assign
values or call functions, but we will eventually meet several other kinds of
statements as well. By default, statements are executed in sequence, one after
another.
A statement causes the compiler to carry out some action. There are 3 different types
of statements – expression statements compound statements and control statements.
Every statement ends with a semicolon.

SIVA SIVNI DEGREE COLLEGE 94 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Declaration is a program statement that serves to communicate to the language


translator information about the name and type of the data objects needed during
program execution.
Expression statement is the simplest kind of statement
which is no more than an expression followed by a semicolon.
An expression is a sequence of operators and operands that specifies computation of
a value.
x=4
is just an expression (which could be part of a larger expression), but
x = 4; is a statement.
Compound statement is a sequence of statements that may be treated as a single
statement in the construction of larger statements.
Labeled statements can be used to mark any statement so that control may be
transferred to the statement by switch statement.
Control statement is a statement whose execution results in a choice being made as
to which of two or more paths should be followed. In other words, the control
statements determine the ‘flow of execution’ in a program.
 Selection statements allow a program to select a particular execution path from a
set of one or more alternatives. Various forms of the if..else statement belong to this
category.
o Iteration statements are used to execute a group of one or more statements
repeatedly. while, for, and do..while statements falls under this group.
o Jump statements cause an unconditional jump to some other place in the
program. goto statement falls in this group
Example: (1) C considers any expression to be a statement if you append a semicolon.
These are called expression statements.
c=a + b;
(2) A compound statement is two or more statements grouped together by enclosing
them in braces; it is also called a block.
{
a=3;
b=4;
c=a+b;
}
(3) the control statements determine the ‘flow of execution’ in a program.
if (a<b)
{
Printf (“\n a is less than b”);
}
Statement may be single or compound (a set of statements) .

SIVA SIVNI DEGREE COLLEGE 95 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Most of the statements in a C program are expression statements. An expression
statement is simply an expression followed by a semicolon. The lines i = 0;
i = i + 1; and printf ("Hello, world!\n"); are all expression statements

Discuss About expression Evaluation


Precedence And Associativity
Evaluation of an expression in C is very important to understand. Unfortunately
there is no ‘BODMAS’ rule in C language as found in algebra. Operators have rules
of precedence and associativity that are used to determine how expressions are
evaluated.
When there is more than one operator in an expression, it is the relative priorities of
the operators with respect to each other that will determine the order in which the
expression will be evaluated. This priority is known as precedence.
The precedence of operators determines the order in which different operators are
evaluated when they occur in the same expression. Operators of higher precedence
are applied before operators of lower precedence.
Consider the following expression: 4 + 3 * 2
the operator ‘*’ has higher precedence than ‘+’, causing the multiplication to be
executed first, then the addition. Hence, the value of the expression is 10.
An equivalent expression is4 + (3 * 2)
Ex: a statement as written below.
Assume that n is a variable of type int:n = 5 – 2 * 7 – 9;
The ‘*’ has a higher precedence than ‘–’ so it is evaluated first, and the statement is
equivalent to:
n = 5 – 14 – 9;
The minus has left-to-right associativity, so the statement is equivalent to: n = –18;

SIVA SIVNI DEGREE COLLEGE 96 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
An example of the use of expression Evaluation Precedence And Associativity
#include <stdio.h>
int main()
{
int a;
int b = 4;
int c = 8;
int d = 2;
int e = 4;
int f = 2;
a = b + c / d + e * f;
/* result without parentheses */
printf(“The value of a is = %d \n”, a);
a = (b + c) / d + e * f;
/* result with parentheses */
printf(“The value of a is = %d \n”, a);
a = b + c / ((d + e) * f);
/* another result with parentheses */
printf(“The value of a is = %d \n”, a);
return 0;
}
Output
The value of a is = 16
The value of a is = 14
The value of a is = 4
What is lvalue and rvalue?
An lvalue is an expression to which a value can be assigned. An rvalue can be defined
as an expression that can be assigned to an lvalue. The lvalue expression is located
on the left side of an assignment statement, whereas an rvalue is located on the right
side of an assignment statement.
The address associated with a program variable in C is called its lvalue; the contents
of that location are its rvalue, the quantity that is supposed to be the value of the
variable. The rvalue of a variable may change as program execution proceeds;
but never its lvalue. The distinction between lvalues and rvalues becomes sharper if
one considers the assignment operation with variables a and b.
a = b;
b, on the right-hand side of the assignment operator, is the quantity to be found at
the address associated with b, i.e., an rvalue. a is assigned the value stored in the
address associated with b. a, on the left-hand side, is the address at which the contents
are altered as a result of the assignment.
a is an lvalue. The assignment operation stores b’s rvalue at a’s lvalue.
What are the differences between l-value and r-value?

SIVA SIVNI DEGREE COLLEGE 97 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Explain About Type Conversion In C


Type conversion (or typecasting) means transfer of data from one data type to
another.Typecasting, or type conversion, is a method of changing an entity from one
data type to another. It is used in computer programming to ensure variables are
correctly processed by a function. An example of typecasting is converting an integer
to a string
There are two types of conversion: implicit and explicit.
Implicit Type Conversion: Also known as „automatic type conversion‟.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid loss of data.
All the data types of the variables are upgraded to the data type of the variable with
largest data type.
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long ->
float -> double -> long double

// An example of implicit conversion


#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
}
Output:
x = 107, z = 108.000000
Explicit Type Conversion
This process is also called type casting and it is user defined. Here the user can type
cast the result to make it of a particular data type.
The syntax in C: (type) expression
Type indicated the data type to which the final result is converted.

SIVA SIVNI DEGREE COLLEGE 98 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
// C program to demonstrate explicit type casting
#include<stdio.h>
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
return 0;
}
Output:
sum = 2
Advantages of Type Conversion
This is done to take advantage of certain features of type hierarchies or type
representations.
It helps us to compute expressions containing variables of different data types.

Here are the steps that you need to follow to compile and execute your first C
program…
1. Start the compiler at C>prompt. The compiler (TC.EXE is usually present in
C:\TC\BIN directory).
2. Select New from the File menu.
3. Type the program.
4. Save the program using F2 under a proper name (say Program1.c).
5. Use alt+f9 to compile and Ctrl + F9 (run) execute the program.
6. Use Alt + F5 to view the output.

SIVA SIVNI DEGREE COLLEGE 99 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
IMPORTANT QUESTIONS
1. Discuss about computer fundamentals
2. Write about classification of computers
3. Draw a neat diagram of anatomy of a computer,
4. Write a short note on memory hierarchy
5. Define operating system & characteristics of os
6. Discuss about operational overview of a cpu.
7. Write about program fundamentals
8. Expalin in deatied Generation and classification of programming languages
9. Explain the process of Compiling, interpreting, loading, linking of a
program,
10. Discuss about developing program
11. Write about Softwaredevelopment.
12. What is Algorithms & charactristics of algorithm
13. Different ways of stating algorithms
14. What are the strategies for designing algorithms
15. Write about Structured programming concept.
16. How to Develop programs in c
17. What are the Parts of simple c program
18. Explain structure of a c program with example
19. Define Comments and explain types of comments
20. What are the Program statements
21. List out C tokens
22. Define Keywords list out keywords
23. DefineIdentifiers?how it is different from varable
24. Define Data type,explain primary data types in c
25. DefineVariables types of variables
26. Define Constants types of constants
27. Define Operators types of operators
28. Define expressions types of expressions
29. What is Expression evaluation–precedence and associativity in c
30. DefineType conversions explain types of it

SIVA SIVNI DEGREE COLLEGE 100 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
UNIT-II
INPUT OUTPUT FUNCTIONS OF C LANGUAGE:
When we are saying Input that means we feed some data into program. This can be
given in the form of file or from command line. C programming language provides
a set of built-in functions to read given input and feed it to the program as per
requirement.
When we are saying Output that means to display some data on screen, printer or
in any file. C programming language provides a set of built-in functions to output
the data on the computer screen.
Functions printf() and scanf() are the most commonly used to display out and take
input respectively
All these input and output functions are declared in header files like <stdio.h>,
<conio.h>
Function Type meaning
 printf() Output Writes formatted text on the screen
 scanf() Input Reads formatted text from keyboard
 getc () Input Reads a character from stream
 putc () Output Writes a character into a stream
 gets () Input Reads a string from keyboard
 puts () output Writes string on to the screen
EXPLAIN ABOUT FORMATTED INPUT AND OUTPUT OPERATIONS
1) clrscr() :-
This function is used to clear the screen. This function‟s prototype has defined in the header
file CONIO.H ( CONIO ==> Console Input Output )
Syntax : clrscr();
2) printf() :-
This function is used to display the text and the values of variables. This function‟s
prototype has defined in the header file STDIO.H
To display the variable‟s value the format string must be used.
( STDIO ==> Standard Input Output )
Syntax :
printf(“ format string “, variables) ;
Ex :
printf(“ Hello \t World “);
printf(“ %d %c”, k, j);
printf(“The marks are %d, %d, %d”, m1, m2, m3 );
Note : The function printf() returns an integer value that is the number of arguments given
to the statement.
Ex :
/* sdfjkshadjfsdjkafkjsadjkfhkasdj sdafhasdfhgasdhfgasdgfgasdfhasdfj
sdafjksadfjasdkhfjasdhkfjhksda */
Ex Programs :
/* My First ‘C’ Program */
# include <stdio.h>
# include <conio.h>
main()
{
clrscr() ;
printf(“Hello” );
printf(“Bhanodaya “) ;
printf(“Welcome “) ;
}

SIVA SIVNI DEGREE COLLEGE 101 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
More about printf statement
There are quite a number of format specifiers for printf. Here are the basic ones:
%d print an int argument in decimal
%ld print a long int argument in decimal
%c print a character
%s print a string
%f print a float or double argument
%e same as %f, but use exponential notation
%g use %e or %f, whichever is better
%o print an int argument in octal (base 8)
%x print an int argument in hexadecimal (base 16)
%% print a single %
3) scanf() :
This function is used to accept the values for the variables while executing the program from
keyboard. This function‟s prototype has defined in the header file STDIO.H
The function printf() returns an integer value that is the number of arguments given to the
statement.
Syntax:
scanf(“formatstring” , &(variables) );
Note :To accept two or more values with a single scanf() they can be seperated by space or
tab or enter key.
Ex :
i) int a;
scanf(“%d”, &a);
ii) int m1, m2, m3;
scanf(“%d%d%d”, &m1, &m2, &m3);
iii) char ch;
scanf(“%c”, &ch);
4)getch() :
This function is used to accept a single character for the variable while executing the
program. But this function does not display the entered character. This function‟s prototype
has defined in the header file CONIO.H
Note : To see the entered character the function getche() can be Used.
Syntax:
(variable) = getch() ;
Ex :
char c;
c = getch();

We can also limit the number of digits or characters that can be input or output, by
adding a number with the format string specifier, like "%1d" or "%3s", the first one
means a single numeric digit and the second one means 3 characters, hence if you
try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is the case
for output.

EXPLAIN ABOUT NON-FORMATTED INPUT AND OUTPUT


Non-formatted input and output can be carried out by standard input–output
library functions in C. These can handle one character at a time. For the input
functions, it does not require <Enter> to be pressed after the entry of the character.
For output functions, it prints a single character on the console.

SIVA SIVNI DEGREE COLLEGE 102 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
READING AND WRITING A CHARACTER
 getchar() is an input function that reads a single character from the standard
input device, ormally a keyboard.
 putchar() is an output function that writes a single character on the standard
output device, the display screen.
 There are two other functions, gets() and puts(), that are used to read and
write strings from and to the keyboard and the display screen, respectively.
A string may be defined as an arranged collection of characters.
getchar() function
It is used to read a single character (char type) from keyboard. The syntax is
char variable name = getchar( );
Example:
char c;
c = getchar( );
For reading an array of characters or a string we can use getchar( ) function.
Example:
#include<stdio.h>
main( )
{
char place[80];
int i;
for(i = 0;( place [i] = getchar( ))! = ‘\n’, ++i);
}
This program reads a line of text.
putchar() function
It is used to display single character.
The syntax is
putchar(char c);
Example:
char c;
c = ‘a’;
putchar(c);
Using these two functions, we can write a very basic program to copy the input, a
character at a time, to the output:
#include <stdio.h>
/* copy input to output */
main(){
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
return 0;
}
gets() & puts() functions
The gets() function reads a line from stdin(standard input) into the buffer pointed
to by str pointer, until either a terminating newline or EOF (end of file) occurs.
The puts() function writes the string str and a trailing newline to stdout.

SIVA SIVNI DEGREE COLLEGE 103 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
#include<stdio.h>
void main() {
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch(); }
When you will compile the above code, it will ask you to enter a string. When you
will enter the string, it will display the value you have entered.
Display a given character.
Solution
#include<stdio.h>
int main(void)
{
int ch;
ch=‘A’;
putchar(ch);
return 0;
}
Output A
#include<stdio.h>
int main(void)
{
int ch;
ch=‘A’;
ch=ch + 1;
putchar(ch);
return 0;
}
Output B
Display the keyed-in character and the next character from the ASCII table.
#include<stdio.h>
int main(void)
{
int ch;
ch=getchar();
ch=ch++;
putchar(ch);
return 0;
}
Input a
Output b
Print a keyed-in character.
#include<stdio.h>
int main(void)
{
putchar(getchar());
return 0; }
Input y
Output y
SIVA SIVNI DEGREE COLLEGE 104 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Difference between scanf() and gets()
The main difference between these two functions is that scanf() stops reading
characters when it encounters a space, but gets() reads space as character too.
If you enter name as Study Tonight using scanf() it will only read and store Study
and will leave the part after space. But gets () function will read it completely.
Explain Escape Sequence Characters (Backslash Character ) In C:
C supports some special escape sequence characters that are used to do special tasks. Escape
sequences are used in input and output functions such as printf and scanf. These are
also called as 'Backslash characters'.
An escape sequence is used to express non printing character like a new line, tab etc. it begin
with the backslash (\) followed by letter like a, n, b, t, v, r, etc. the commonly used escape
sequence are
\a : for alert
\n : new line
\0 : null
\b : backspace
\f : form feed
\? : Question mark
\f : horizontal tab
\r : carriage return
\’ : single quote
\v : vertical tab
\” : quotation mark
\\ : back slash
If any of these are included in the format string, the corresponding ASCII control
code is sent to the screen, or output device, which should produce the effect listed. In
most cases, the programmer only needs to remember \n for new line.
Ex:
printf( “%3d\n%3d\n%3d\n”, 5, 25, 125 );
printf( “Pi is %4.2f to 2dp\n”, pi);

EXPLAIN ABOUT PREPROCESSORS IN C


Preprocessor commands: The commands which start with a hash (#) symbol are
called Preprocessor commands. Ex : # include <stdio.h> # include “ conio.h ” #
define PI 3.14159
[A preprocessor statement is a statement before the main program, which begins
with # symbol.]

SIVA SIVNI DEGREE COLLEGE 105 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
C Pre-processor directives:
Before a C program is compiled in a compiler, source code is processed by a
program called pre-processor. This process is called pre-processing.
Commands used in pre-processor are called pre-processor directives and they begin
with “#” symbol.
Below is the list of pre-processor directives that C programming language offers.
Preprocessor Syntax/Description

Syntax: #define
Macro This macro defines constant value and can be any of the basic data
types.
Syntax: #include <file_name>
Header file
The source code of the file “file_name” is included in the main
inclusion
program at the specified place.
Syntax: #ifdef, #endif, #if, #else, #ifndef
Conditional
Set of commands are included or excluded in source program before
compilation
compilation with respect to the condition.
Syntax: #undef, #pragma
Other directives #undef is used to undefine a defined macro variable. #Pragma is used
to call a function before and after main function in a C program.
A program in C language involves into different processes.
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
}

Output: value of height : 100


value of number : 3.140000
value of letter : A
value of letter sequence : ABC

SIVA SIVNI DEGREE COLLEGE 106 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

DEFINE CONTROL FLOW STATEMENTS


As we know that the code in the C program is executed sequentially from the first
line of the program to its last line. That is, the second statement is executed after the
first; the third statement is executed after the second, so on.in some cases we want
only selected statements to be executed.
Control flow statements enable programmers to conditionally execute a particular
block of code. There are three types of control statements: decision control
(branching), iterative (looping), and jump statements. While branching means
deciding what actions have to be taken, looping, on the other hand, decides how
many times the action has to be taken. Jump statements transfer control from one
point to another point.

Control statements embody the decision logic that tells the executing program what
action to carry out next depending on the values of certain variables or expression
statements.
The control statements include selection, iteration, and jump statements that work
together to direct program flow.
A selection statement is a control statement that allows choosing between two or
more execution paths in a program. The selection statements in C are the if statement,
the if-else statement, and the switch statement. These statements allow
us to decide which statement to execute next. Each decision is based on a Boolean
expression (also called a condition or test expression), which is an expression that
evaluates to either true or false. The result of the expression determines which
statement is executed next.

SIVA SIVNI DEGREE COLLEGE 107 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Looping The programming mechanism that executes a series of statements
repeatedly a given number of times, or until a particular condition is fulfilled, is
called a loop. The construct used for loop is known as iteration statement. C language
offers three language elements to formulate iteration statements:
while, do-while, and for.
Jump statements transfer the control to another point of the program. Jump
statements include goto, break, continue, and return.
Explain About Selection/Branching/Decision Control Statements
C supports decision control statements that can alter the flow of a sequence of
instructions. These statements help to jump from one part of the program to another
depending on whether a particular condition is satisfied or not. These decision
control statements include:
(A) if statement, (b) if–else statement, (c) nested –if (d) if–else–if ladder, and (d)
switch–case statement.

For one-way selection. if..... without else part is used. The if...else... construct is used
to implement two-way selection.
Nested-if and if...elseif... ladder is used to implement nested selection construct.
For implementing multi-way selection switch case is used.
 One-way decision statements do a particular thing or they do not.
 Twoway decision statements do one thing or do another.
 Multiway decision statements can do one of many different things
depending on the value of an expression.
if Statement
if statement is the simplest decision control statement that is frequently used in
decision making.
The general form of a simple if statement is shown in Fig.

The if block may include 1 statement or n statements enclosed within curly


brackets. First the test expression is evaluated. If the test expression is true, the
statements of the if block are executed, otherwise these statements will be skipped
and the execution will jump to statement x.
The statement in an if block is any valid C language statement, and the test
expression is any valid C language expression that evaluates to either true or false.

SIVA SIVNI DEGREE COLLEGE 108 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
In addition to simple relational expressions, we can also use compound expressions
formed using logical operators. Note that there is no semi-colon after the test
expression. This is because the condition and statement should be put together as a
single statement.

EX: #include<stdio.h>#include<conio.h>
intmain()
{
int x=10;if (x>0)
{
printf("\nx=%d",x);
}
getch():
return0;
}
Note:In case the statement block contains only one statement, putting curly
bracketsbecomes optional. If there are more than one statement in the statement
block, putting curly brackets becomes mandatory.
if–else Statement
This is also one of the most useful conditional statements used in C to check
conditions.
Two-way decisions are handled with if-else statements that either do one particular
thing or do another. Similar to one-way decisions, the decision here is based on a
test expression. The form of a two-way decision is as follows:
if(TestExpr)
stmtT;
else
stmtF;

SIVA SIVNI DEGREE COLLEGE 109 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

In the if–else construct, first the test expression is evaluated. If the expression is
true, statement block 1 is executed and statement block 2 is skipped. Otherwise, if
the expression is false, statement block 2 is executed and statement block 1 is
ignored.
In any case after the statement block 1 or 2 gets executed, the control will pass to
statement x. Therefore, statement x is executed in every case.

/* Program to demonstrate if-else statement.*/


//Write a program to find whether a number is even or odd.
#include <stdio.h> int main()
{
int a;
printf("\n Enter the value of a : ");
scanf("%d", &a);
if(a%2==0)
printf("\n %d is even", a);
else
printf("\n %d is odd", a);
return 0; }

SIVA SIVNI DEGREE COLLEGE 110 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Nested if
When any if statement is written under another if statement,this cluster is called a
nested if.

Write a program using nested if statement


#include <stdio.h>
void main()
{
int a = 10;
if(a % 2 == 0)
{
if(a % 5 == 0)
{
printf("Number is Divisible by 5 and 2");
}
printf("Number is Divisible by 2");
}
}
Multi-Way Decisions
Multi-way decision statements use if-else-if nested if or switch statements. They are
used to evaluate a test
expression that could have several possible values. if-elseif statements, Switch
statements are often used to choose between ranges of values.
If–else–if Statement or else –if ladder
C language supports if–else–if statements to test additional conditions apart from the
initial test expression. The if–else–if construct works in the same way as a normal if
statement.
Note that it is not necessary that every if statement should have an else block as C
supports simple if statements. After the first test expression or the first if branch, the
programmer can have as many else–if branches as he wants depending on the
expressions that have to be tested.

SIVA SIVNI DEGREE COLLEGE 111 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Syntax of nested else-if ladder statement


if(condition 1)
{
-----
-----
}
else if(condition 2)
{
-----
-----
}
else if(condition 3)
{
-----
}
else
{
----- }
For example, the following code tests whether a number entered by the user is
negative, positive, or equal to zero.
int main() {
int num;
printf("\n Enter any number : ");
scanf("%d", &num);
if(num==0)
{
printf("\n The value is equal to zero");
}
else if(num>0)
{
printf("\n The number is positive");
}
else {
printf("\n The number is negative");
}
getch(); return 0; }

SIVA SIVNI DEGREE COLLEGE 112 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Note :that if the first test expression evaluates to a true value, i.e., num=0, then the
rest of the statements in the code will be ignored and after executing the printf
statement that displays „The value is equal to zero‟, the control will jump to return
0 statement.

Write about switch–case Statement


 A switch-case statement is a multi-way decision statement that is a simplified
version of an If–else–if block.
 The power of nested if–else–if statements lies in the fact that it can evaluate more
than one expression in a single logical structure. switch statements are mostly used
in two situations:
 When there is only one variable to evaluate in the expression
 When many conditions are being tested for
 When there are many conditions to test, using the if and else–if constructs
becomes complicated and confusing. Therefore, switch case statements are often
used as an alternative to long if statements that compare a variable to several
„integral‟ values (integral values are those values that can be expressed as an
integer, such as the value of a char). Switch statements are also used to handle the
input given by the user.
The general form of a switch statement is shown in Fig

In above syntax, switch, case, break are keywords.


 Statements inside case expression need not to be closed in braces.
 Break statement causes an exit from switch statement.
 Default case is optional case. When neither any match found, it executes.
Advantages of using a switch–case Statement
Switch–case statement is preferred by programmers due to the following reasons:
 Easy to debug
 Easy to read and understand
 Ease of maintenance as compared to its equivalent if–else statements
 Like if–else statements, switch statements can also be nested
 Executes faster than its equivalent if–else construct

SIVA SIVNI DEGREE COLLEGE 113 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Rules for using switch statement
 The expression (after switch keyword) must yield an integer value i.e the expression
should be an integer or a variable or an expression that evaluates to an integer.
 The case label values must be unique.
 The case label should be integer or character constant. The case label must end with
a colon (:)
 Each compound statement of a switch case should contain break statement to exit
from case.
 The next line, after the case statement, can be any valid C statement.
 The switch statement enables you to choose one course of action from a set of possible
actions, based on the result of an integer expression.
 The case labels can be in any order and must be constants.
 No two case labels can have the same value.
 The default is optional and can be put anywhere in the switch construct.
 The case constants must be integer or character constants.
 The expression must evaluate to an integral type.
 The break statement is optional. If a break statement is omitted in any case of a switch
statement, the program flow is followed through the next case label.
Write a program to determine whether the entered character is a vowel or not.
int main() {
char ch;
clrscr();
printf("\n Enter any character : ");
scanf("%c", &ch);
switch (ch)
{
case „A‟:
case „a‟:
printf("\n %c is VOWEL", ch); break;
case „E‟:
case „e‟:
printf("\n %c is VOWEL", ch); break;
case „I‟:
case „i‟:
printf("\n %c is VOWEL", ch); break;
case „O‟:
case „o‟:
printf("\n %c is VOWEL", ch); break;
case „U‟:
case „u‟:
printf("\n %c is VOWEL", ch); break;
default: printf("\n %c is not a vowel", ch);
}
getch(); return 0;}

Note that there is no break statement after case A, so if the character A is entered then
control will execute the statements given in case a.

SIVA SIVNI DEGREE COLLEGE 114 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
EXPLAIN ABOUT ITERATIVE STATEMENTS IN C
 Iterative statements are used to repeat the execution of a sequence of statements
until the specified expression becomes false.
 A loop allows one to execute a statement or block of statements repeatedly. There
are mainly two types of iterations or loops – unbounded iteration or unbounded loop
and bounded iteration or bounded loop. In bounded iteration, repetition is
implemented by constructs that allow a determinate number of iterations. That is,
bounded loops should be used when we know, ahead of time, how many times we
need to loop.
 C provides for construct as bounded loop. There are also many occasions when one
does not know, ahead of time, how many iterations may be required. Such occasions
require unbounded loops.
 C provides two types of unbounded loops: while loop and do...while loop. These
types of loops are also known as indeterminate or indefinite loops.
A loop declaration and execution can be done in following ways.
o Check condition to start a loop
o Initialize loop with declaring a variable.
o Executing statements inside loop.
o Increment or decrement of value of a variable.
C supports three types of iterative statements also known as looping statements.
They are
*while loop *do–while loop *for loop
TYPES OF LOOPING STATEMENTS:
 Basically, the type of looping statements depends on the condition checking
mode. Condition checking can be made in two ways as: Before loop and after
loop. So, there are 2(two) types of looping statements.
 Entry controlled loop
 Exit controlled loop
1. Entry controlled loop: In such type of loop, the test condition is checked first
before the loop is executed. Some common examples of these looping statements
are:
 while loop
 for loop
2. Exit controlled loop: In such type of loop, the loop is executed first. Then
condition is checked after block of statements are executed. The loop executed at
least one time compulsorily.
Some common example of this looping statement is :
 do-while loop

SIVA SIVNI DEGREE COLLEGE 115 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
for loop statement :
This is an entry controlled looping statement. In this loop structure, more than one
variable can be initialized. One of the most important features of this loop is that the
three actions can be taken at a time like variable initialization, condition checking and
increment/decrement. The for loop can be more concise and flexible than that of
while and do-while loops.
The for loop is executed as follows:
1. It first evaluates the initialization code.
2. Then it checks the condition expression.
3. If it is true, it executes the for-loop body.
4. Then it evaluates the increment/decrement condition and again follows from
step 2.
5. When the condition expression becomes false, it exits the loop.
Features:
 More concise
 Easy to use and Highly flexible
 More than one variable can be initialized.
 More than one increment/decrement can be applied.
 More than two conditions can be used.

The following code shows how to print the first n numbers using a for loop.
#include <stdio.h>
#include<conio.h>
int main()
{
int i, n; clrscr();
printf("\n Enter the value of n :");scanf("%d", &n); for(i=1;i<=n;i++)
printf("\n %d", i);getch();
return 0;
}

while loop
o The while loop provides a mechanism to repeat one or more statements while a
particular condition is true.
o This is an entry controlled looping statement. It is used to repeat a block of
statements until condition becomes true.

SIVA SIVNI DEGREE COLLEGE 116 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

In above syntax, Note that in the while loop, the condition is tested before any of the
statements in the statement block is executed. If the condition is true, only then the
statements will be executed, otherwise if the condition is false, the control will jump
to statement y, that is the immediate statement outside the while loop block.

#include<stdio.h>
#include<conio.h>
int main()
{
int i = 1;
clrscr(); while(i<=10)
{
printf("\n %d", i);
i = i + 1; // condition updated
}
getch();
return 0;
}
Note that initially i = 1 and is less than 10, i.e., the condition is true, so in the while
loop the value of i is printed and its value is incremented by 1. When i=11, the
condition becomes false and the loop ends.
Consider the two versions of the same program that prints the sum of digits of a
number.
int main()
{
int n, s=0, r;
printf(“Enter the Number”);
scanf(“%d”, &n);
while(n>0)
{
r=n%10;
s=s+r;
n=n/10;
}
printf(“\nSum of digits %d”, s);
return 0;}

SIVA SIVNI DEGREE COLLEGE 117 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

do–while Loop

 This is an exit controlled looping statement.


 The do–while loop is similar to the while loop.
The only difference is that in a do–while loop, the test condition is tested at the
end of the loop. As the test condition is evaluated at the end, this means that the
body of the loop gets executed at least one time (even if the condition is false).

SIVA SIVNI DEGREE COLLEGE 118 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

 Note that the test condition is enclosed in parentheses and followed by a semi-colon.
The statements in the statement block are enclosed within curly brackets. The curly
brackets are optional if there is only one statement in the body of the do–while loop.
 The do–while loop continues to execute while the condition is true and when the
condition becomes false, the control jumps to the statement following the do–while
loop.
 The major disadvantage of using a do–while loop is that it always executes at least
once, so even if the user enters some invalid data, the loop will execute.
However, do–while loops are widely used to print a list of options for menu-driven
programs.
int main()
{
int c=5;
do
{
printf(“Hello”);
c++;
} while(c<5);
return 0;}
Output Hello
Nested Loops:
A nested loop refers to a loop that is contained within another loop. If the program
has to repeat a loop more than once, it is a good candidate for a nested loop. In
nested loops, the inside loop (or loops) executes completely before the outside
loop’s next iteration. It must be remembered that each inner loop should be enclosed
completely in the outer loop; overlapping loops are not allowed.
You can use one or more loops inside any other while, for, or do...while loop.
Looping in a loop is called Nesting of Loops.
Syntax:
for (loop)
{
while (loop
{
Statements;
}
Statements;
}

SIVA SIVNI DEGREE COLLEGE 119 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
void main()
{
int i,j,n;
clrscr();
printf("Enter number of rows: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
getch(); }
Output:
1
12
123
1234
12345
The variant of the preceding program is
#include <stdio.h>
int main()
{
int row,col, k=1;
for(row=1;row<=4;++row)
{
for(col=1;col<=row;++col)
printf(“%d \t”, k++);
printf(“\n”);
}
return 0; }
It will print output the following on the screen.
1
23
456
7 8 9 10
Write About Special Control(Jumpping) Statements
There are certain control statements which terminate either a loop or a function.
There are three such statements, namely: return, break, and continue.
Break Statement in C
 Loop: The break statement is used to stop the loop statement from running.
 Switch: When using the break statement in a switch-case, it must be used in each instance.
If this is not the case, control will be passed at a next case.
The break statement will end control of the innermost loop in a nested loop, and execution
will begin on the line after the innermost loop block.
When the compiler encounters a break statement, the control passes to the statement
that follows the loop in which the break statement appears.
Its syntax is quite simple, just type keyword break followed by a semi-colon.
break;

SIVA SIVNI DEGREE COLLEGE 120 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
The example given below shows the manner in which break statement is used to
terminate the loop in which it is embedded.

int main()
{
int i = 0; while (i<=10)
{
if (i==5)
{
break;
}
printf("\t %d", i);i = i + 1;
} return 0;}

Output
01234
As soon as i becomes equal to 5, the break statement is executed and the control jumps
to the statement following the while loop. Hence, the break statement is used to exit
a loop from any point within its body, bypassing its normal termination expression.
continue Statement
Like the break statement, the continue statement can only appear in the body of a
loop. When the compiler encounters a continue statement, then the rest of the
statements in the loop are skipped and the control is unconditionally transferred to
the loop-continuation portion of the nearest enclosing loop. Its syntax is quite simple,
just type keyword continue followed by a semi-colon.
continue;
Again like the break statement, the continue statement cannot be used without an
enclosing for, while, or do–while loop. When the continue statement is encountered
in the while loop and in the do–while loop, the control is transferred to the code that
tests the controlling expression. However, if placed within a for loop, the continue
statement causes a branch to the code that updates the loop variable.
For example, consider the following code:

#include <stdio.h>
int main()
{
int i;
for(i=0; i<= 10; i++)
{
if (i==5)
{
continue;
}
printf("\t %d", i);
}
return 0;
}

Output
0 1 2 3 4 6 7 8 9 10
SIVA SIVNI DEGREE COLLEGE 121 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Note that the code is meant to print numbers from 0 to 10. But as soon as i becomes
equal to 5, the continue statement is encountered, so the printf () statement is skipped
and the control passes to the expression that increments the value of i.
goto Statement
 The goto statement is another type of control statement supported by C. The control
is unconditionally transferred to the statement associated with the label specified in
the goto statement. The form of a goto statement is goto label_name;
 Because the goto statement can interfere with the normal sequence of processing, it
makes a program more difficult to read and maintain. Often, a break statement, a
continue statement, or a function call can eliminate the need for a goto statement.
 A statement label is defined in exactly the same way as a variable name, which is a
sequence of letters and digits, the first of which must be a letter.
The statement label must be followed by a colon (:) just like a case label in a switch.
Like other statements, the goto statement ends with a semicolon.
Goto Statement Syntax
The label specified after the goto statement in C Programming is the location where
we place the code block to execute. From the below syntax, you can understand that
we can place the label anywhere in the program. It doesn’t matter if you put before
the goto or after.

Some examples of goto statements are in order


The following program is used to find the factorial of a number.
#include <stdio.h>
int main()
{
int n, i;
long int f=1;
printf(“\n Enter the number:”);
scanf(“%d”,&n);
if(n<0) goto end;
for(i=1; i<=n; i++)
f=f*i;
printf(“\n FACTORIAL IS %ld”, f);
end:
getch();
return 0;
}

SIVA SIVNI DEGREE COLLEGE 122 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Write about return statement The return type is used in the definition of a function
to set its returned value and the return statement is used to terminate execution of
the function.
The return statement has two forms. Functions with return type void use the
following form: return;
Functions with non-void return type use the following form:
return expression;
Here, expression yields the desired return value. This value must be convertible to
the return type declared for the function. This will be explained in more detail in the
functions.
int main()
{
printf("Hello World!");
return 0;
}
Write about the exit() in c
The exit() function is used to terminate a process or function calling immediately in
the program. It means any open file or function belonging to the process is closed
immediately as the exit() function occurred in the program.
The exit() function is the standard library function of the C, which is defined in
the stdlib.h header file. So, we can say it is the function that forcefully terminates the
current program and transfers the control to the operating system to exit the
program.
The exit(0) function determines the program terminates without any error message,
and then the exit(1) function determines the program forcefully terminates the
execution process.
Following are the main points of the exit function in C programming as follows:
1. We must include the stdlib.h header file while using the exit () function.
2. It is used to terminate the normal execution of the program while encountered
the exit () function.
3. The exit () function calls the registered atexit() function in the reverse order of
their registration.
4. We can use the exit() function to flush or clean all open stream data like read or
write with unwritten buffered data.
5. It closed all opened files linked with a parent or another function or file and can
remove all files created by the tmpfile function.
6. The program's behaviour is undefined if the user calls the exit function more
than one time or calls the exit and quick_exit function.
7. The exit function is categorized into two parts: exit(0) and exit(1).
Syntax of the exit() function
void exit ( int status);
The exit() function has no return type.
int status: It represents the status value of the exit function returned to the parent
process.

SIVA SIVNI DEGREE COLLEGE 123 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Following is the C program for use of exit() function −
#include<stdio.h>
void main()
{
char ch;
printf("B: Breakfast"); printf("L: Lunch");
printf("D: Dinner"); printf("E: Exit"); printf("Enter your choice:");
do{
ch = getchar();
switch (ch) {
case 'B' : printf ("time for breakfast");
break;
case 'L' : printf ("time for lunch");
break;
case 'D' : printf ("time for dinner");
break;
case 'E' :
exit(0); /* return to operating system */
}
} while (ch != 'B' && ch != 'L' && ch != 'D');
return 0; }
Output
When the above program is executed, it produces the following result −
B: Breakfast
L: Lunch
D: Dinner
E: Exit
Enter your choice:D
Time for dinner
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, num;
printf ( " Enter the last number: "); scanf ( " %d", &num);
for ( i = 1; i<num; i++) {
if ( i == 6 )
/* use exit () statement with passing 0 argument to show termination of the
program without any error message. */
exit(0);
else
printf (" \n Number is %d", i);
}
return 0; }
Output
Enter the last number: 10
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
SIVA SIVNI DEGREE COLLEGE 124 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
ARRAYS
Define array and write about how to declare and initialize array
 An array is a collection of individual data elements that are ordered, fixed in size,
and homogeneous. An array is considered to be a derived data type.
 An array is a collection of similar data elements. These data elements have the same
data type.
 An array is a data structure that is a collection of variables of one type that are
accessed through a common name. Each element of an array is given a number by
which we can access that element which is called an index. It solves the problem of
storing a large number of values and manipulating them.
 The elements of the array are stored in consecutive memory locations and are
referenced by an index (also known as the subscript). The subscript is an ordinal
number which is used to identify an element of the array.
For example, we can define an array name marks to represent a set of marks obtained
by a group of students. A particular value is indicated by writing a number called
index number or subscript in brackets after the array name.
Example: int Marks [6];
There are two categories in array
1. Numeric type array: this array is declared by any numeric value of datatype
Ex: int halltickets [10];
2. Character type array: this array is declared by any character value of datatype
Ex: char name [20];
Each array has following parts.
Declaration of array:
In array declaration we must define
• The type of data it can hold, i.e., int, char, double, float, etc.
• Name of the array
• Number of subscripts in the array [ ] or [ ][ ] or [ ][ ][ ]
• Total number of memory locations of array (size)
Initialization of Array:
Initialization means assigning or giving a value to array elements.
An Array can be initialized in several ways.
• At the time of declaration
ex: int a[4]={10,20,30,40};
• using Assignment operator
ex: int a[4]; a[0]=10;a[1]=20];
• Using scanf ()
Ex: int a[4];
scanf(“%d”,&a[0]);
EX: int marks [10];

SIVA SIVNI DEGREE COLLEGE 125 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

How to access the elements of an array


To access all the elements, we must use a loop. That is, we can access all the elements
of an array by varying the value of the subscript into the array.

Type of Arrays
• One / Single Dimensional Array
• Two Dimensional Array
• Multi-Dimensional Array
Explain one / single dimensional array with suitable example
The array which is used to represent and store data in a linear form is called as 'single
or one dimensional array.' it can represent either one row or one column. When a list
of data items are stored under a variable name using only one subscript and such a
variable is called a single- subscripted variable or one dimensional array.
 Declaration of array:
A one-dimensional array declaration is a data type followed by an identifier with a
bracketed constant integral expression.
The value of the expression, which must be positive, is the size of the array. It specifies
the number of elements in the array. The array subscripts can range from 0 to (size –
1). The lower bound of the array subscripts is 0 and the upper bound is (size –1).
Thus, the following relationships hold.
int a[size]; /* memory space for a[0],a[1],…, a[size –1] allocated */
lower bound = 0
upper bound = size –1
size = upper bound + 1
The syntax for declaration of a one-dimensional array is data_type array_name
[SIZE];
 All the array elements hold values of type <data type>.
 The size of the array is indicated by <SIZE>, the number of elements in the array.
<SIZE> must be an int constant or a constant expression.
Example: int rno[60];
int a[3] = {2, 3, 5};
char ch[20] = "programming" ;
float stats[3] = {5003.23, 1940.32, 123.20} ;

SIVA SIVNI DEGREE COLLEGE 126 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 Total Size (in Bytes):
Total size = length of array * size of data type
In above example, a is an array of type integer which has storage size of 3 elements.
The total size would be 3 * 2 = 6 bytes.
Memory Allocation: for one dimensional array

Initialization of Array: An Array can be initialized in several ways.

Along with Declaration:


Datatype array-name [size]= {e1,e2,e3,….en};
Ex: int marks [6]={12,14,15,17,10,19};
Using Assignment Operator after declaration:
Array-name [index] = value ;
Ex: marks[0]=12; or scanf (“%d”,&marks[0]); marks[1]=14;
or scanf(“%d”,&marks[1]);
Using scanf( ) in loop: Another way is…by using scanf() in loop statement
for (i=0;i<6; i++)
{
scanf(“%d”,&a[i]);
}
Automatic sizing While initializing, the size of a onedimensional array can be
omitted as shown.
int arr[] = {3,1,5,7,9};
Here, the C compiler will deduce the size of the array from the initialization
statement.
From the above initialization statement, the size of the array is deduced to be 5.
Calculating the Length of an Array
The length of an array is given by the number of elements stored in it. The general
formula to calculate the length of an array is
Length = upper_bound – lower_bound + 1
Where upper_bound is the index of the last element and lower_bound is the index of
the first element in the array.

SIVA SIVNI DEGREE COLLEGE 127 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Example 3.2 Let Age [5] be an array of integers such that
Age [0] = 2, Age [1] = 5, Age [2] = 3, Age [3] = 1, Age [4] = 7

Show the memory representation of the array and calculate its length.
Solution : The memory representation of the array Age [5] is given as below.

Write a program to read and display n numbers using an array.


#include <stdio.h>
#include <conio.h> int main()
{
int i, n, arr[20]; clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
}
printf("\n The array elements are ");
for(i=0;i<n;i++)
printf("\t %d", arr[i]);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The array elements are 1 2 3 4 5
or
#include <stdio.h>
#define ARRAY_SIZE 10
int main()
{
int index, a[ARRAY_SIZE];
for(index = 0; index < ARRAY_SIZE; index++)
{
a[index] = 0;
printf(“a[%d] = %d\n”, index, a[index]);
}
printf(“\n”);
return 0;
}

SIVA SIVNI DEGREE COLLEGE 128 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
The output from the above example is as follows:
a[0] = 0
a[1] = 0
a[2] = 0
a[3] = 0
a[4] = 0
a[5] = 0
a[6] = 0
a[7] = 0
a[8] = 0
a[9] = 0
Write a program to print the position of the smallest number of n numbers using
arrays.
int main() {
int i, n, arr[20], small, pos;
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements : ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
small = arr[0];
pos =0;
for(i=1;i<n;i++)
{
if(arr[i]<small)
{
small = arr[i];
pos = i; }}
printf("\n The smallest element is : %d", small);
printf("\n The position of the smallest element in the
array is : %d", pos);
return 0; }
Output
Enter the number of elements in the array: 5 Enter the elements: 7 6 5 14 3
The smallest element is : 3
The position of the smallest element in the array is: 4
// Program to find the average of n numbers using arrays
#include <stdio.h>
int main() {
int marks[10], i, n, sum = 0, average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i < n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the sum variable
sum += marks[i];
}
average = sum / n;
printf("Average = %d", average); return 0; }
SIVA SIVNI DEGREE COLLEGE 129 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
LIST OF INBUILT C FUNCTIONS IN CTYPE.H FILE:
 “ctype.h” header file support all the below character functions in C language.

Functions Description
 checks whether character is alphabetic
 You can get a different non-zero integer when alphabetic character
is passed to isalpha () on your system. But, when you pass non-
alphabetic character to isalpha (), it always returns 0.
isalpha()
 The isdigit() function checks whether a character is numeric
character (0-9) or not.
 Returns 1 if argument is a numeric character.
 Returns 0 if argument is not a numeric.
isdigit()
 Checks whether character is alphanumeric
 isalnum() Return Value
 Returns 1 if argument is an alphanumeric character.
isalnum()  Returns 0 if argument is neither an alphabet nor a digit.

 Checks whether character is space


 The isspace () function checks whether a character is a white-space
character or not.
 If an argument (character) passed to the isspace () function is a
isspace() white-space character, it returns non-zero integer. If not, it returns
0.

 Checks whether character is lower case


 Returns 1 if argument is a lower character.
 Returns 0 if argument is not a lower character.
islower()
 Checks whether character is upper case
 Returns 1 if argument is a upper character.
 Returns 0 if argument is not a l upper character.
isupper()
 Checks whether character is alphabetic & converts to lower case
 The tolower () function takes an uppercase alphabet and convert it
to a lowercase character.
 If the arguments passed to the tolower () function is other than an
uppercase alphabet, it returns the same character that is passed to
tolower() the function.

SIVA SIVNI DEGREE COLLEGE 130 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Checks whether character is alphabetic & converts to upper case
 The toupper () function takes an uppercase alphabet and convert it
to a lowercase character.
 If the arguments passed to the toupper () function is other than an
uppercase alphabet, it returns the same character that is passed to
toupper() the function.

Example: C isdigit () function


#include <stdio.h>
#include <ctype.h>
int main()
{
char c;
c='5';
printf ("Result when numeric character is passed: %d", isdigit(c));
c='+';
printf ("\n Result when non-numeric character is passed: %d", isdigit(c));
return 0;
}
Example program for character functions function in C:
int main()
{
char ch;
printf ("Enter any character : ");
scanf("%c", &ch);
if ( isalpha ( ch ) )
printf ( "\n Entered character is alphabetic" ) ;
else
printf ( "\n Entered character is not alphabetic" ) ;
if ( isdigit ( ch ) )
printf (“\n Entered character is digit" ) ;
else
printf ( "\n Entered character is not digit" ) ;
if ( islower( ch ) )
printf ( "\n Entered character is lower case character") ;
else
printf("\n Entered character is not lower case character");
if ( isupper( ch ) )
printf ( "\n Entered character is lower case character") ;
else
printf("\n Entered character is not lower case character");
getch( );
return 0;
}

SIVA SIVNI DEGREE COLLEGE 131 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Write about Character array and string
 A string is a series of characters treated as a single unit. Strings in C are represented
by arrays of characters. A string may include letters, digits and various special
characters such as +, -, *, / and $. String literals or string constants in C are written
in double quotation marks.
 The string can be defined as the one-dimensional array of characters terminated
by a null ('\0'). The end of the string is marked with a special character, the null
character, which is a character whose bits are all zero, i.e.,
 a NUL (not a NULL).The character array or the string is used to manipulate text
such as word or sentences.
 Each character in the array occupies one byte of memory, and the last character
must always be The termination character ('\0') is important in a string since it is
the only way to identify where the string ends.
 When we define a string as char s [10], the character s [10] is implicitly initialized
with the null in the memory.
Declaration of a character /String of array
Strings can be declared like one-dimensional arrays. For
example,
char str[30];
char text[80];
There are two ways to Initializing a string in c language.
1. By char array
2. By string literal
Character array:
Let's see the example of declaring string by char array in C language.
char ch [20]={'s', 'i', 'v', 'a', 's', 'i', 'v', 'a', 'n', 'i', '\0'};
#include<stdio.h>
#include <string.h>
int main()
{
char ch[11]= {'s', 'i', 'v', 'a', 's', 'i', 'v', 'a', 'n', 'i', '\0'};
printf ("Char Array Value is: %s\n", ch);
return 0;
}
string literal
While declaring string, size is not mandatory. So we can write the above code as
given below:
char ch []={'s', 'i', 'v', 'a', 's', 'i', 'v', 'a', 'n', 'i', '\0'};
We can also define the string by the string literal in C language.

For example:
char ch []="sivasivani";
In such case, '\0' will be appended at the end of the string by the compiler.

SIVA SIVNI DEGREE COLLEGE 132 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Char Array Value is: sivasivani


String Literal Value is: sivasivani
Accessing or Read Strings:
To read a string, we can use scanf ( ) function with format specifier %s.
Reading Strings
If we declare a string by writing char str[100];
Then str can be read by the user in three ways:
1. using scanf function,
2. using gets() function, and
3. using getchar(),getch()or getche() function repeatedly.
Ex: char name[50];
scanf("%s",name);
#include <string.h>
int main(){
char ch[11]= {'s', 'i', 'v', 'a', 's', 'i', 'v', 'a', 'n', 'i', '\0'};
char ch2[11]="sivasivani";
printf ("Char Array Value is: %s\n", ch);
printf ("String Literal Value is: %s\n", ch2);
return 0; }

The above format allows accepting only string which does not have any blank space,
tab, new line, forming feed, carriage return.
Displaying or Write Strings:
To write a string, we can use printf ( ) function with format specifier %s.
Writing Strings
Strings can be displayed on the screen using the following three ways:
1. using printf() function,
2. using puts() function, and
3. using putchar() function repeatedly.
Strings can be displayed using printf() by writing
Ex: printf("%s", str);

SIVA SIVNI DEGREE COLLEGE 133 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
The following program illustrates the use of the %s Conversion specifier.
#include <stdio.h>
int main()
{
char s[]=“Hello, World”;
printf(“>>%s<<\n”,s);
printf(“>>%20s<<\n”,s);
printf(“>>%-20s<<\n”,s);
printf(“>>%.4s<<\n”,s);
printf(“>>%-20.4s<<\n”,s);
printf(“>>%20.4s<<\n”,s);
return 0;
}
This program produces the output
>>Hello, World<<
>> Hello, World<<
>>Hello, World <<
>>Hell<<
>>Hell <<
>> Hell<<
The >> and << symbols are included in this program so that the limits of the output
fields are clearly visible in the output.
COMMON STRING HANDLING OPERATIONS /FUNCTIONS

 strcpy ( ): this string function is used to copy the one string characters to another
string.
( which copies second string to first string).
Syntax : strcpy(string1,string2);
 strlen ( ); this string function is used to find the length (no. of characters) of the
given string.
Syntax : strlen(string);
 strrev( ): this string function is used to convert the given string characters into
reverse order.
Syntax : strrev(“string”);
 strlwr( ):- This function is used to convert the given string characters in to lower
caseformat.
Syntax : strlwr((“string”))
 strupr( ):- This function is used to convert the given string characters in to
uppercaseformat.
Syntax : strupr((“string”))
 strcmp( ): this string function is used to compare two strings. (which returns the
value 0 when both strings are equal, returns 1(positive) when strin1 is greater
than string 2, returns negative when the string 1 is less than string 2).
Syntax : strcmp(string1,string2);

SIVA SIVNI DEGREE COLLEGE 134 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 strcat( ): this string function is used to concatenate(add) two strings. (Second string
can beadded to first string ).
Syntax : strcat(string1,string2);
FunctionName Description

strcat ( ) Concatenates two string.i.e Concatenates str2 at theend of


str1.strcat ( str2, str1 ); - str1 is concatenated at
the end of str2.
strcpy ( ) Copies a string from source to destination.
i.e Copies str2 into str1
strcpy ( str1, str2) – It copies contents of str2 into str1.
strncpy ( ) Copies a string from source to destination. copies given
number of characters of one string toanother
strncpy ( str1, str2, 4) – It copies first 4 characters ofstr2 into
str1.
strlen ( ) Returns the length of a string. Gives the length of str1.
strlen( ) function counts the number of characters in agiven
string and returns the integer value.
Int Strlen(str1);
strcmp ( ) Compares two strings. Returns 0 if str1 is same as str2.
Returns <0 if strl <str2.
Returns >0 if str1 > str2.
int strcmp ( str1,str2 );
strlwr ( ) Returns upper case letter to lower case. convertsstring to
lowercase
char strlwr(str1);
strupr ( ) eturns lower case letter to upper case. converts stringto
uppercase
char strupr(str1);
strrev ( ) Returns reverses the given string
char strrev(str1);

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 ( destination, source);
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
SIVA SIVNI DEGREE COLLEGE 135 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
If destination string length is less than source string, entire source string value won‟t
be copied 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.
Example : 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 (destination, source );
Example :
strcat ( str2, str1 );
- str1 is concatenated at the end of str2. strcat ( str1, str2 );
- str2 is concatenated at the end of str1.
• 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.
Program : The following program is an example of strcat() function
#include <stdio.h> #include <string.h> int main( )
{
char source[ ] = “ sai” ;
char target[ ]= “ welcome to” ;
printf (“\n Source string = %s”, source);
printf ( “\n Target string = %s”, target ) ;
strcat ( target, source ) ;
printf ( “\n Target string after strcat( ) = %s”, target ) ;
}
Output :
Source string = sai
Target string = welcome to
Target string after strcat() = welcome to sai
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);

SIVA SIVNI DEGREE COLLEGE 136 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
5. 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.
Program : In this program, string ”MODIFY This String To LOwer” is converted into
lower case using strlwr( ) function and result is displayed as “modify this string to
lower”.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “MODIFY This String To Lower”;
printf(“%s\n”, strlwr (str));
return 0;
}
Output :
modify this string to lower
6. 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.
Program : In this program, string ”Modify This String To Upper” is converted into
uppercase using strupr( ) function and result is displayed as “MODIFY THIS
STRING TO UPPER”.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “Modify This String To Upper”;
printf(“%s\n”, strupr(str));
return 0;
}
Output : MODIFY THIS STRING TO UPPER
7. 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.
Example :
char name[20]=”ftl”; then strrev(name)= ltf
Program : In below program, string “Hello” is reversed using strrev( ) function and
output is displayed as “olleH”.

SIVA SIVNI DEGREE COLLEGE 137 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = “Hello”;
printf(“String before strrev( ) : %s\n”, name);
printf(“String after strrev( ) : %s”, strrev(name));
return 0;
}
Output :
String before strrev( ) : Hello String after strrev( ) : olleH

Multi-Dimentinal Arrays
Write about two dimensional arrays with suitable examples
 Arrays can have more than one dimension. Double dimensional arrays can
represent the data in the form of rows and columns means taking two indexes.
 The array which is used to represent and store data in a tabular form is called
as 'two dimensional array.' Such type of array specially used to represent data
in a matrix form. It is also called as 'multidimensional array.'
 The following syntax is used to represent two dimensional arrays.
Syntax: Data-type array_name [row size] [column-size];
Example: int a[3][3];
 In above example, a is an array of type integer which has storage size of 3 *
3matrix.
 The total size would be 3 * 3 * 2 = 18 bytes.
Memory Allocation :

SIVA SIVNI DEGREE COLLEGE 138 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Initialization of 2D Array: An Array can be initialized in several ways.
 Along with Declaration:
Datatype array-name [row][col] = {e1,e2,e3,….en};
Ex: int marks[2][3]={12,14,15,17,10,19};
 Using Assignment Operator after declaration:
array-name [row index][col index]= value ;
Ex: marks[0][0]=12; or scanf(“%d”,&marks[0][0]);
marks[1][1]=17; or scanf(“%d”,&marks[1][1]);
 Using scanf() in loop: Another way is…by using scanf() in loop statement
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
scanf(“%d”,&a[i][j]);
}
}
Write a program to print the elements of a 2D array.
int main()
{
int arr[2][2] = {12, 34, 56,32};
int i, j; for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t", arr[i][j]); }
printf("\n");
}
return 0;
}
Output
12 34
56 32
/* Program to demonstrate two dimensional array.*/
int main() {
int a[3][3], i, j; clrscr();
printf("\n\t Enter matrix of 3*3 : "); for(i=0; i<3; i++)
{
for(j=0; j<3; j++) {
scanf("%d",&a[i][j]); //read 3*3 array
}
}
printf("\n\t Matrix is : \n");for(i=0; i<3; i++)
{
for(j=0; j<3; j++) {
printf("\t %d",a[i][j]); //print 3*3 array
}
printf("\n");
} getch();
return 0;
}

SIVA SIVNI DEGREE COLLEGE 139 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

Write a C program to find sum of two matrices


#include <stdio.h>
#include<conio.h>
void main()
{
float a[2][2], b[2][2], c[2][2];
int i,j;
clrscr();
printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there is an array
of 'n' dimension, 'n' numbers of loops are needed for inserting data to array.*/
for(i=0;i<2;I++)
for(j=0;j<2;j++)
{
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
scanf("%f",&b[i][j]);
}
/* accessing corresponding elements of two arrays. */ for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays. */
}
/* To display matrix sum in order. */ printf("\nSum Of Matrix:"); for(i=0;i<2;++i)
{
for(j=0;j<2;++j)
printf("%f", c[i][j]);
printf("\n");
}
getch();
}
Discuss about N-Dimensional Array:
More than 2-dimensional arrays are treated as n- dimensional arrays.
Example:
int a[2][3][4];
Here a represents two 2-dimensional arrays and each of these 2-d arrays contains
3 rows and 4 columns.
The individual elements are:
a[0][0][0],
a[0][0][1],a[0][0][2],a[0][1][0]…………a[0][3][2]
a[1][0][0],a[1][0][1],a[1][0][2],
a[1][1][0]…………..a[1][3][2]
the total no. of elements in the above array is 2*3*4=24.
Multi-dimensional arrays can represent the data in the form of rows and
columns by taking two or more indexes (two and three dimensional arrays). Three
dimensional arrays use three indexes.
SIVA SIVNI DEGREE COLLEGE 140 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Declaration: The general format of the multi-dimensional array is..
Data-type array-name [size 1][size 2] .… [Size n];
Ex: int a[2][2][3];
int a[ ][ ][ ]= {(10,20,30),(40,50,60),(70,80,90),(11,22,33)};
Here the array size is 2x2x3 means (2x2) 4 rows and 3 columns, 3imum 12 elements
with 24 bytes of memory space. These are defined as same as One Dimensional
arrays.
Initialization:
int a[2][4][3]={ {
{1,2,3}, {4,5}, {6,7,8}, {9} }, { {10,11}, {12,13,14}, {15,16}, {17,18,19} } }
The values of elements after this initialization are as:
a[0][0][0]:1 a[0][0][1]:2 a[0][0][2]:3
a[0][1][0]:4 a[0][1][1]:5 a[0][1][2]:0
a[0][2][0]:6 a[0][2][1]:7 a[0][2][2]:8
a[0][3][0]:9 a[0][3][1]:0 a[0][3][2]:0
a[1][0][0]:10 a[1][0][1]:11 a[1][0][2]:0
a[1][1][0]:12 a[1][1][1]:13 a[1][1][2]:14
a[1][2][0]:15 a[1][2][1]:16 a[1][2][2]:0
a[1][3][0]:17 a[1][3][1]:18 a[1][3][2]:19
Note:
The rule of initialization of multidimensional arrays is that last subscript varies
most frequently and the first subscript varies least rapidly.
Ex: int test [2][3][4];
int test[2][3][4] =
{
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},{{13, 4, 56, 3}, {5, 9, 3, 5},{3, 1, 4, 9}}
};
Write a program to read and display a 2 \ 2 \ 2 array.
int main(){
int array[2][2][2], i, j, k;
clrscr();
printf("\n Enter the elements of the matrix"); for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
scanf("%d", &array[i][j][k]);
}
}
}
printf("\n The matrix is : "); for(i=0;i<2;i++)
{
printf("\n"); for(j=0;j<2;j++)
{
printf("\n"); for(k=0;k<2;k++)
printf("\t array[%d][%d][%d] = %d", i, j, k, array[i] [j][k]);
}
}
getch(); return 0;
}
SIVA SIVNI DEGREE COLLEGE 141 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Output
Enter the elements of the matrix 1 2 3 4 5 6 7 8
The matrix is
arr[0][0][0] = 1 arr[0][0][1] = 2
arr[0][1][0] = 3 arr[0][1][1] = 4
arr[1][0][0] = 5 arr[1][0][1] = 6
arr[1][1][0] = 7 arr[1][1][1] = 8
IMPORTANT QUESTIONS
1. explain Non-formatted input and output functions
2. explain about Formatted Input and output functions
3. explain Escape Sequences
4. define and explain Control Statements in c
5. what are the Selection Statements in c?
6. explain about –if, if-else statements in c
7. what is nested if give an example
8. write about nested if-else
9. define operator and write about comma operator
10. define and explain about conditional operator
11. list out operators with examples
12. explain switch case statement with example
13. define loop and list out Iterative Statements
14. explain while loop with example
15. explain for loop with example
16. explain do-while loop with example
17. explain Special Control Statement–goto in c
18. write about break keyword
19. Write about continue keyword
20. Wrote about return keyword
21. Write about exit keyword
22. Explain about Arrays in detailed
23. Define Strings? Explain declaration and initialization of string
24. Explain in detailed One-dimensional Arrays with example
25. Explain Character Arrays
26. Give an example for Functions from ctype.h
27. Multidimensional Arrays.

SIVA SIVNI DEGREE COLLEGE 142 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
UNIT-III
FUNCTIONS
C language provides an approach in which you can declare and define a group of
statements once in the form of a function and it can be called and used whenever
required.
Define Function? Need of the function and advanteages of functions ?
A function is a self-contained block of program statements that performs a particular
task. It is often defined as a section of a program performing a specific job.
 Function: A function is a reusable block of statements that gets executed on
calling. It can be treated as sub program. Or
 The function is a self-contained block of statements which performs a
particular task of a same kind.
 C enables its programmers to break up a program into segments commonly
known as functions, each of which can be written more or less independently of the
others.
 Every C program has at least one function, which is main(), and all the most
trivial programs can define additional functions.
Why are functions needed?
The use of functions provides several benefits.
 First, it makes programs significantly easier to understand and maintain by
breaking up a program into easily manageable chunks. (modularity)
 Second, the main program can consist of a series of function calls rather than
countless lines of code. It can be executed as many times as necessary from different
points in the main program. (readability)
 The third benefit is that well-written functions may be reused in multiple
programs. This enables code sharing. (code reusability)
 Fourth, functions can be used to protect data. This is related with the concept
of local data. Local data is the data described within a function. They are available
only within a function when the function is being executed.(integrity)
 Fifth, by using functions different programmers working on one large project
can divide the workload by writing different functions.
How functions are works:
 We can see that main () calls a function named func1 (). Therefore, main ()
is known as the calling function and func1 () is known as the called
function. The moment the compiler encounters a function call, the control
jumps to the statements that are a part of the called function.
After the called function is executed, the control is returned to the calling program.

Types of functions:
There are 2(two) types of functions as:
1. Pre-Defined (Built in) Functions
2. User Defined Functions

SIVA SIVNI DEGREE COLLEGE 143 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Explain about c standard library functions (built in funtions)
 C Standard library functions or simply C Library functions are inbuilt functions in
C programming.
 The prototype (function declaration) and data definitions of these functions are
present in their respective header files. To use these functions we need to include
the header file in our program. For example,
 If you want to use the printf () function, the header file <stdio.h> should be
included.
 Some of Examples: scanf ( ), printf ( ), getch ( ), clrscr ( ), strcpy ( ), pow ( ), sqrt ( ),
isalpha ( )
#include
<stdio.h>
int main ()
{
printf ("Catch me if you can.");
}

Library Functions in Different Header Files


C Header Files Description
<ctype.h> Character type functions
<math.h> Mathematics functions
<stdio.h> Standard Input/output functions
<stdlib.h> Standard Utility functions
<string.h> String handling functions
<time.h> Date time functions
write about C Math Functions
C Programming allows us to perform mathematical operations through the
functions defined in <math.h> header file. The <math.h> header file contains
various methods for performing mathematical operations such as sqrt(), pow(),
ceil(), floor() etc.

Function Description Example

sqrt(4.0) is 2.0
sqrt(x) square root of x sqrt(10.0) is 3.162278

exp(1.0) is 2.718282
exp(x) exponential (ex) exp(4.0) is 54.598150

log(2.0) is 0.693147
log(x) natural logarithm of x (base e) log(4.0) is 1.386294

log10(10.0) is 1.0
log10(x) logarithm of x (base 10) log10(100.0) is 2.0

fabs(2.0) is 2.0
fabs(x) absolute value of x fabs(-2.0) is 2.0

SIVA SIVNI DEGREE COLLEGE 144 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
ceil(9.2) is 10.0
ceil(x) rounds x to smallest integer ceil(-9.2) is -9.0
not less than x
floor(9.2) is 9.0
floor(x) rounds x to largest integer not floor(-9.2) is -10.0
greater than x
pow(x,y) pow(2,2) is 4.0
x raised to power y (xy)
fmod(13.657, 2.333) is
fmod(x) remainder of x/y as floating- 1.992
point number
sin(x) sine of x (x in radian) sin(0.0) is 0.0

cos(x) cosine of x (x in radian) cos (0.0) is 1.0

tan(x) tangent of x (x in radian) tan(0.0) is 0.0

#include <math.h>
int main() {
printf ("%f\n",sqrt(10.0));
printf ("%f\n",exp(4.0));
printf ("%f\n", log(4.0));
printf ("%f\n",log10 (100.0));
printf ("%f\n",fabs (-5.2));
printf ("%f\n",ceil(4.5));
printf ("%f\n",floor(-4.5));
printf ("%f\n",pow(4.0,.5));
printf ("%f\n",fmod(4.5,2.0));
printf ("%f\n", sin(0.0));
printf ("%f\n", cos(0.0));
printf ("%f\n",
tan(0.0));
return 0; }
Explain about time.h header file in C
The time.h header file contains definitions of functions to get and manipulate date
and time information.
It describes three time-related data types.
 clock_t: clock_t represents the date as an integer which is a part of the calendar time.
 time_t:: time_t represents the clock time as an integer which is a part of the calendar
time.
Program to calculate the time taken to add two numbers program.
#include <time.h>
int main(void) {
time_t start, end;
start = time(NULL);
int a, b;
scanf ("%d %d", &a, &b);
printf ("Sum of %d and %d is %d\n",a, b, a + b);
end = time(NULL);
printf ("Time taken to print sum is %.2f seconds", difftime (end, start));
}
SIVA SIVNI DEGREE COLLEGE 145 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM

Function Name Explanation


This function returns the date and time in the format day
month date hours: minutes: seconds year.
Eg: Sat Jul 27 11:26:03 2019.
asctime() asctime() function returns a string by taking struct tm
variable as a parameter.

Function Name Explanation

This function returns the processor time consumed by a


clock() program

This function returns the date and time in the format day
month hours:minutes:seconds year
ctime() Eg: Sat Jul 27 11:26:03 2019
time is printed based on the pointer returned by
Calendar Time

This function returns the difference between the times


difftime() provided.

This function prints the UTC (Coordinated Universal


Time) Time and date. Format for both gmtime() and
gmtime() asctime() is same

This function returns the calendar-time equivalent using


time() data-type time_t.

This function helps to format the string returned by other


time functions using different format specifiers
strftime()

USER DEFINED FUNCTIONS


The functions which are declared and defined by the user or programmer for a
program or problem are known as 'User defined functions'.
While using functions, we will be using the following terminologies:
• When a function is called, the code contained in that function is executed, and when
the function has finished executing, control returns to the point at which that function
was called.
• A function f that uses another function g is known as the calling function, and g is
known as the called function.
• The inputs that a function takes are known as arguments/parameters.
• When a called function returns some result back to the calling function, it is said to
return statement that result.

SIVA SIVNI DEGREE COLLEGE 146 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
• The calling function may or may not pass parameters to the called function. If the
called function accepts arguments, the calling function will pass parameters, else
not.
Explain function elements with syntax
• Function Prototype (Declaration)
• Function Definition
• Function Call
• return statement
1. Function Prototype (Declaration)
Function declaration is a declaration statement that identifies a function‟s name, a
list of arguments that it accepts, and the type of data it returns.
Syntax: return_data_type function_name (data_type_list);
EX: int add ();
Int add (int, int);
There are three basic parts in this declaration.
 Function_name this is the name given to the function and it follows the same
naming rules as that for any valid variable in C.
 return_data_type this specifies the type of data given back to the calling construct
by the function after it executes its specific task.
 data_type_list: this list specifies the data type of each of the variables, the values of
which are expected to be transmitted by the calling construct to the function.
The following are some examples of declaration statements.
 float FtoC(float faren);
 double power(double, int);
 int add(int);
 void add(void);
 void sum(int);
2. Function Call
The function call statement invokes the function. When a function is invoked,
the compiler jumps to the called function to execute the statements that are a
part of that function. Once the called function is executed, the program
control passes back to the calling function.
A function call statement has the following syntax:
function_name (variable1, variable2 ...);
Ex: add(a,b); or add(2,5); or add();
The following points are to be noted while calling a function:
 Function name and the number and the type of arguments in the function
call must be same as that given in the function declaration and the function
header of the function definition.
 Names (and not the types) of variables in function declaration, function call,
and header of Function definition may vary.
 Arguments may be passed in the form of expressions to the called function.
In such a case, Arguments are first evaluated and converted to the type of
formal parameter and then the Body of the function gets executed.
 If the return type of the function is not void, then the value returned by the
called function May be assigned to some variable as given below.
variable_name = function_name (variable1, variable2 ...);
3. Function Definition
Function definition consists of a function header that identifies the function,
followed by the body of the function containing the executable code for that
function.
SIVA SIVNI DEGREE COLLEGE 147 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
When a function is defined, space is allocated for that function in the
memory.
A function definition comprises of two parts:
• Function header
• Function body
The syntax of a function definition can be given as:
return_data_type function_name (data_type variable1, data_type
variable2...)//HEADER
{
............. //BODY
Statements;
.............
return (variable);
}

EX:
add (int x, int y)
{
return x+y;
}
 Note that the number of arguments and the order of arguments in the function
header must be the same as that given in the function declaration statement.
 While return_data_type function_name (data_type variable1, data_type
variable2...) is known as the function header, the rest of the portion comprising of
program statements within the curly brackets { } is the function body which
contains the code to perform the specific task.
 Note that the function header is same as the function declaration. The only
difference between the two is that a function header is not followed by a semi-colon.
 The list of variables in the function header is also referred to as the formal
parameters.
 Return type denote the type of value that function will return and return type is
optional if omitted it is assumed to be integer by default.
 return statement
The general form of the return statement is as follows:
return expression;
or
return (expression);
where expression must evaluate to a value of the type specified in the function
header for the return value. The expression can be any desired expression as long
as it ends up with a value of the required type.
int sum(int, int);
int main ()
{
int a=5, b=10,res;
res=sum(a,b);
printf(“result=%d”, res);
return 0;
}
int sum(int x, int y)
{
return x+y; }
SIVA SIVNI DEGREE COLLEGE 148 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Explain the main categories of the user defined functions
1. Function with no arguments and no return values.
2. Function with no arguments and a return value.
3. Function with arguments and no return values.
4. Function with arguments and return values.
1. Function with no arguments and no return values:
syntax:
void funct (void);
main ( )
{
funct ( );
}
void funct ( void );
{
}
NOTE: There is no communication between calling and called function.
Functions are executed independently, they read data & print result in
same block.
Example:
void link (void) ;
int main ()
{
link ();
}
void link ( void );
{
printf (“ link the file “)
}
2. Function with no arguments and a return value: This type of functions
has no arguments but a return value
example:
int msg (void) ;
int main ( )
{
int s = msg ( );
printf( “summation = %d” , s);
}
int msg ( void )
{
int a, b, sum ; sum = a+b ; return (sum) ;
}
NOTE: Here called function is independent, it read the value from the
keyboard, initialize and return a value .Both calling and called function are
partly communicated with each other.
3. Function with arguments and no return values:
Here functions have arguments so, calling function send data to called
function but called function does no return value. such functions are partly
dependent on calling function and result obtained is utilized by called
function .

SIVA SIVNI DEGREE COLLEGE 149 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Example:
void msg ( int , int );
int main ( )
{
int a,b;
a= 2; b=3;
msg( a, b);
}
void msg ( int a , int b)
{
int s ;
sum = a+b;
printf (“sum = %d” , s ) ;
}
4. Function with arguments and return value:
Here calling function of arguments that passed to the called function and called
function return value to calling function.
example:
int msg ( int , int ) ;
int main ( ) {
int a, b;
a= 2; b=3;
int s = msg (a, b);
printf (“sum = %d” , s ) ;
}
int msg( int a , int b)
{
int sum ;
sum =a+b ;
return (sum);
}
DEFINE ACTUAL ARGUMENTS AND FORMAL ARGUMENTS
Actual Arguments:
1. Arguments which are mentioned in the function in the function call are known as
calling function.
2. These are the values which are actual arguments called to the function.
It can be written as constant , function expression on any function call which return
a value.
ex: funct (6,9); , funct ( a,b );
Formal Arguments:
1. Arguments which are mentioned in function definition are called dummy or
formal argument.
2. These arguments are used to just hold the value that is sent by calling function.
3. Formal arguments are like other local variables of the function which are created
when function call starts and destroyed when end function.
Basic difference between formal and local argument are:
a) Formal arguments are declared within the ( ) where as local variables are declared
at beginning.
b) Formal arguments are automatically initialized when a value of actual argument
is passed.
c) Where other local variables are assigned variable through the statement inside the
function body.
SIVA SIVNI DEGREE COLLEGE 150 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM

Note: Order, number and type of actual argument in the function call should be
matched with the order , number and type of formal arguments in the function
definition .
Explain the concept of Passing Parameters to Functions
There are two ways in which arguments or parameters can be passed to the called
function. Call by value The values of the variables are passed by the calling function
to the called function.
Call by reference The addresses of the variables are passed by the calling function
to the called function.
Call by Value
In this method, the called function creates new variables to store the value of the
arguments passed to it. Therefore, the called function uses a copy of the actual
arguments to perform its intended task.
 If the called function is supposed to modify the value of the parameters passed to
it, then the change will be reflected only in the called function.
 In the calling function, no change will be made to the value of the variables. This is
because all the changes are made to the copy of the variables and not to the actual
variables. To understand this concept, consider the code given below. The function
add () accepts an integer variable num and adds 10 to it. In the calling function, the
value of num = 2.
 In add (), the value of num is modified to 12 but in the calling function, the change
is not reflected.
EX:
void add(int n);
int main () {
int num = 2;
printf("\n The value of num before calling the function = %d",
num);add(num);
printf("\n The value of num after calling the function = %d",
num);
return 0; }
void add(int n) {
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2
Following are the points to remember while passing arguments to a function
using the call-by value method:
 When arguments are passed by value, the called function creates new variables of
the same data type as the arguments passed to it.
 The values of the arguments passed by the calling function are copied into the newly
created variables.
 Values of the variables in the calling functions remain unaffected when the
arguments are passed using the call-by-value technique.

SIVA SIVNI DEGREE COLLEGE 151 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Note
C supports only call by value mechanism which means the values of the actual
arguments are conceptually copied to the formal parameters. If it is required to alter
the actual arguments in the called function, the addresses of the arguments must be
passed explicitly.
NOTE:
Whatever change made in called function not affects the values in calling function.
Call by Reference
 When the calling function passes arguments to the called function using the call-by-
value method, the only way to return the modified value of the argument to the
caller is explicitly using the return statement. A better option is to pass arguments
using the call-by-reference technique.
 In this method, we declare the function parameters as references rather than normal
variables. When this is done, any changes made by the function to the arguments it
received are also visible in the calling function.
 To indicate that an argument is passed using call by reference, an asterisk (*) is
placed after the type in the parameter list.
 Hence, in the call-by-reference method, a function receives an implicit reference to
the argument, rather than a copy of its value. Therefore, the function can modify the
value of the variable and that change will be reflected in the calling function as well.
The following code illustrates this concept.
Output
The value of num before calling the function = 2 The value of num in the called
function = 12 The value of num after calling the function = 12
Advantages
The advantages of using the call-by-reference technique of passing arguments
include:
 Since arguments are not copied into the new variables, it provides greater time and
space efficiency.
 The function can change the value of the argument and the change is reflected in
the calling function.
 A function can return only one value. In case we need to return multiple values, we
can pass those arguments by reference, so that the modified values are visible in the
calling function.
NOTE:
In call by address mechanism whatever change made in called function affect the
values in calling function.
void add(int *);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(&num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add(int *n)
{
*n = *n + 10;
printf("\n The value of num in the called function = %d", *n); }

SIVA SIVNI DEGREE COLLEGE 152 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Disadvantages
 However, the drawback of using this technique is that if inadvertent changes are
caused to variables in called function then these changes would be reflected in
calling function as original values would have been overwritten.
Explain the concept of Passing Parameters to Functions
There are two ways in which arguments or parameters can be passed to the called
function. Call by value The values of the variables are passed by the calling function
to the called function.
Call by reference The addresses of the variables are passed by the calling function to
the called
function.
Call by Value
In this method, the called function creates new variables to store the value of the
arguments passed to it. Therefore, the called function uses a copy of the actual
arguments to perform its intended task.
If the called function is supposed to modify the value of the parameters passed to it,
then the change will be reflected only in the called function.
In the calling function, no change will be made to the value of the variables. This is
because all the changes are made to the copy of the variables and not to the actual
variables.
To understand this concept, consider the code given below. The function add ()
accepts an integer variable num and adds 10 to it. In the calling function, the value of
num = 2.
In add (), the value of num is modified to 12 but in the calling function, the change is
not reflected.
EX:#include<stdio.h>#include<conio.h>
Void add(int n);
intmain()
{
int num = 2;
printf("\nThevalue ofnumbeforecallingthefunction =%d", num);add(num);
printf("\nThevalueofnumaftercallingthefunction=%d",num);
return0;
}
Void add(intn)
{
n =n +10;
printf("\nThevalue ofnumin thecalledfunction=%d",n);
}
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2
Following are the points to remember while passing arguments to a function using
the call-by value method:
 When arguments are passed by value, the called function creates new variables of
the same data type as the arguments passed to it.
 The values of the arguments passed by the calling function are copied into the
newly created variables.
 Values of the variables in the calling functions remain unaffected when the
arguments are passed using the call-by-value technique.
SIVA SIVNI DEGREE COLLEGE 153 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Note
C supports only call by value mechanism which means the values of the actual
arguments are conceptually copied to the formal parameters. If it is required to alter
the actual arguments in the called function, the addresses of the arguments must be
passed explicitly.
NOTE:
Whatever change made in called function not affects the values in calling function.
Call by Reference
When the calling function passes arguments to the called function using the call-by-
value method, the only way to return the modified value of the argument to the caller
is explicitly using the return statement. A better option is to pass arguments using
the call-by-reference technique.
In this method, we declare the function parameters as references rather than normal
variables. When this is done, any changes made by the function to the arguments it
received are also visible in the calling function.
To indicate that an argument is passed using call by reference, an asterisk (*) is placed
after the type in the parameter list.
Hence, in the call-by-reference method, a function receives an implicit reference to
the argument, rather than a copy of its value. Therefore, the function can modify the
value of the variable and that change will be reflected in the calling function as well.
The following code illustrates this concept.
Output
The value of num before calling the function = 2 The value of num in the called
function = 12
The value of num after calling the function = 12
Advantages
 The advantages of using the call-by-reference technique of passing arguments
include:
 Since arguments are not copied into the new variables, it provides greater time
and space efficiency.
 The function can change the value of the argument and the change is reflected in
the calling function.
 A function can return only one value. In case we need to return multiple values,
we can pass those arguments by reference, so that the modified values are visible
in the calling function.
NOTE:
In call by address mechanism whatever change made in called function affect the
values in calling function.
voidadd(int *);
intmain()
{
int num = 2;
printf("\nThevalue ofnumbeforecallingthefunction =%d", num);add(&num);
printf("\nThevalue ofnumaftercallingthe function =%d", num);
return0;
}
voidadd(int*n)
{
*n =*n +10;
printf("\nThevalueofnumin thecalledfunction=%d", *n);
}
SIVA SIVNI DEGREE COLLEGE 154 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Disadvantages
However, the drawback of using this technique is that if inadvertent changes are
caused to variables in called function then these changes would be reflected in
calling function as original values would have been overwritten.
Pass arrays to a function
In C programming, you can pass an entire array to functions.
Pass Individual Array Elements
Passing array elements to a function is similar to passing variables to a function.
Example 1: Pass Individual Array Elements
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}
int main() {
int ageArray[] = {2, 8, 4, 12};

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}
Output
8
4
Here, we have passed array parameters to the display() function in the same way
we pass variables to a function.
Pass Arrays to Functions
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[])
{
float sum = 0.0;

for (int i = 0; i < 6; ++i) {


sum += num[i];
}
return sum;
}
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an
argument.
result = calculateSum(num);
SIVA SIVNI DEGREE COLLEGE 155 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
However, notice the use of [] in the function definition.
float calculateSum(float num[])
{
... .. }
This informs the compiler that you are passing a one-dimensional array to the
function.
Scope of variables
The region of the program over which the declaration of an identifier is visible is
called the scope of the identifier. The scope relates to the accessibility, the period of
existence, and the boundary of usage of variables declared in a statement block or a
function. These features in turn define whether a variable is local or global in nature.
Concept of Global and Local Variables
There are two common terms related to the visibility or accessibility of a variable.
They are global and local variables.
Global and local are the terms related with lifetime. Lifetime is the period during
execution of a program in which a variable or function exists.
 Variables declared within the function body are called local variables. They have
local scope. Local variables are automatically created at the point of their
declaration within the function body and are usable inside the function body.
These variables exist only inside the specific function that creates them. They are
unknown to other functions and to the main program. The existence of the local
variables ends when the function completes its specific task and returns to
the calling point. They are recreated each time a function is executed or called.
 Variables declared outside of all the functions of a program and accessible by any
of these functions are called global variables. The existence and region of usage of
these variables are not confined to any specific function body.
They are implemented by associating memory locations with variable names. Global
variables are created at the beginning of program execution and remain in existence
all through the period of execution of the program. These variables are
known to all functions in the program and can be used by these functions as many
times as may be required. They do not get recreated if the function is recalled. Global
variables do not cease to exist when control is transferred from a function. Their v
alue is retained and is available to any other function that accesses them.
All global variables are declared outside of all the functions.
There is no general rule for where outside the functions these should be declared, but
declaring them on top of the code is normally recommended for reasons of scope, as
explained through the given examples. If a variable of the same name is declared both
within a function and outside of it, the function will use the variable that is declared
within it and ignore the global one. If not initialized, a global variable is initialized
to zero by default. As a matter of style, it is best to avoid variable names that conceal
names in an outer scope;the potential for confusion and error is too great. Moreover,
the use of global variables should be as few as possible.
Scope Rules
The region of the program over which the declaration of an identifier is accessible is
called the scope of the identifier. The scope relates to the accessibility, the period of
existence, and the boundary of usage of variables declared in a program.
Scopes can be of four types.
 block
 file
 function
 function prototype
SIVA SIVNI DEGREE COLLEGE 156 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
The following sections describe the scope associated with variables.
Block scope
This means that the identifier can only be used in the block in which it is declared.
These variables are created at the point of their declaration inside the block and cease
to exist outside it. Outside the block, these variables are unknown and nonexistent.
For blocks within blocks, termed as nested blocks, variables declared outside the
inner blocks are accessible to the nested blocks, provided these variables are not
redeclared within the inner block. The redeclaration of variables within the blocks
bearing the same names as those in the outer block, masks the outer block variables
while executing the inner blocks.
In general, it is always better to use different names for variables not common to outer
and inner blocks to avoid unforced errors. The following are some examples
illustrating the scope rules in blocks.
Example
Write a program that illustrates the scope rules in blocks.
#include <stdio.h>
int main()
{
int x= 3; /* variable declaration in outer
block */
printf(“\n in outer block x = %d before\ executing
inner block”, x);
{
int x= 45; /* variable declaration in inner
block */
printf(“\n in inner block x = %d”, x);
}
printf(“\n in outer block x = %d after executing\
inner block”, x);
return 0;
}
Output
in outer block x = 3 before executing inner block in inner block x = 45
in outer block x = 3 after executing inner block
This program shows that because the variable x has been redeclared as 45 in the inner
block, a local variable gets created in the inner block. This variable is only accessible
and known to the inner block.
Functions are considered as named block. Variables declared within a function block
can be used anywhere within the function in which they are defined. The variable x
declared in outer block has the block scope. Like blocks, functions can either be
defined in parallel, where they are placed one after the other and a function can be
called from any other function. But C does not allow functions to be nested, i.e. a
function cannot be defined within another function definition.
Function scope
This applies only to labels. Normally labels are used with goto statement. It simply
means that labels can be used anywhere within the function in which they are
defined. This includes use before definition.
File scope
This means that the identifier can be used anywhere in the current file after the
declaration of the identifier.

SIVA SIVNI DEGREE COLLEGE 157 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
This applies to functions and all variables declared outside functions. File scope
variable is also known as global variable. File scope identifiers may be hidden by the
block scope declarations having same name.
Explain briefly about storage classes in c
 To completely define a variable one needs to mention its type along with its storage
class. In other words we can say not only variables have a data type but also they
have ‘storage classes.
 Compiler identifies the physical location within the computer where the string of
bits which represents the variable’s values are stored from the variable name itself.
 Generally there are two kinds of locations in a computer where such a value can be
present, these are Memory and CPU registers.
 The storage class of a particular variable determines in which of the above two
locations the variable’s value is stored.
 There are four properties by which storage class of a variable can be
recognized.These are scope, default initial value, scope and life.
 A variable’s storage class reveals the following things about a variable
1. Where the variable is stored.
2. What is the initial value of the variable if the value of the variable is not
specified?
3. What is the scope of the variable (To which function or block the variable is
available).
4. What is the life of particular variable (Up to what extent the variable exists in
a program).
In C language, each variable has a storage class which decides the following things:
 scope i.e where the value of the variable would be available inside a program.
 default initial value i.e if we do not explicitly initialize that variable, what will be
its default initial value.
 lifetime of that variable i.e for how long will that variable exist.
 Memory location where it is stored in the memory
The following storage classes are most often used in C programming,

1. Automatic variables(auto)
2. External variables(extern)
3. Static variables(static)
4. Register variables(register)
SIVA SIVNI DEGREE COLLEGE 158 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM

Automatic variables: auto


A variable declared inside a function without any storage class specification, is by
default an automatic variable. They are created when a function is called and are
destroyed automatically when the function's execution is completed. Automatic
variables can also be called local variables because they are local to a function. By
default they are assigned garbage value by the compiler.
1. Scope: Variable defined with auto storage class are local to the function block
inside which they are defined.
2. Default Initial Value: Any random value i.e garbage value.
3. Lifetime: Till the end of the function/method block where the variable is
defined.
4. Memory location:RAM
In the above two functions declaration statements are equivalent as both declare
variables x and y as automatic variables.
Syntax to declare automatic variable is:
auto datatype variablename;
Example:
auto int i;

The following program illustrates the work of automatic variables.


void test();
void main() {
test();
test();
test();
}
void test()
{
auto int k=10;
printf(“%d\n”,k);
k++; }
Output:
10
10
10
In the above program when the function test() is called for the first time ,variable k is
created and initialized to 10. When the control returns to main(), k is destroyed.
When function test() is called for the second time again k is created , initialized and
destroyed after execution of the function. Hence automatic variables came into
existence each time the function is executed and destroyed when execution of the
function completes.

SIVA SIVNI DEGREE COLLEGE 159 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
External or Global variable: extern
 A variable that is declared outside any function is a Global Variable. Global
variables remain available throughout the program execution. By default, initial
value of the Global variable is 0(zero). One important thing to remember about
global variable is that their values can be changed by any function in the program.
 External variables differ from automatic, register and static variables in the context
of scope, external variables are global on the contrary automatic, register and static
variables are local. External variables are declared outside all functions, therefore
are available to all functions that want to use them.
1. Scope: Global i.e everywhere in the program. These variables are not bound by
any function, they are available everywhere.
2. Default initial value: 0(zero).
3. Lifetime: Till the program doesn't finish its execution, you can access global
variables.
4. Memory Location: RAM
#include<stdio.h>
int number; // global variable
void main()
{
number = 10;
printf("I am in main function. My value is %d\n", number);
fun1();
fun2();
}
fun1()
{
number = 20;
printf("I am in function fun1. My value is %d", number); }

fun2()
{
printf("\nI am in function fun2. My value is %d", number);
}
I am in function main.
My value is 10 I am in function fun1.
My value is 20 I am in function fun2.
My value is 20
Here the global variable number is available to all three functions and thus, if one
function changes the value of the variable, it gets changed in every function.
Note: Declaring the storage class as global or external for all the variables in a
program can waste a lot of memory space because these variables have a lifetime till
the end of the program. Thus, variables, which are not needed till the end of the
program, will still occupy the memory and thus, memory will be wasted.

With extern keyword


The extern keyword is used with a variable to inform the compiler that this variable
is declared somewhere else. The extern declaration does not allocate storage for
variables.

SIVA SIVNI DEGREE COLLEGE 160 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Example using extern in same file
int x; //Global variable x
int main()
{
extern int x; //informs the compiler that it is defined somewhere else
x = 10;
printf("%d", x);
}
Static variables: static
 A static variable tells the compiler to persist/save the variable until the end of
program. Instead of creating and destroying a variable every time when it comes
into and goes out of scope, static variable is initialized only once and remains
into existence till the end of the program.
 A static variable can either be internal or external depending upon the place of
declaration.
 Scope of internal static variable remains inside the function in which it is
defined.
 External static variables remain restricted to scope of file in which they are
declared.
They are assigned 0 (zero) as default value by the compiler.
1. Scope: Local to the block in which the variable is defined
2. Default initial value: 0(Zero).
3. Lifetime: Till the whole program doesn't finish its execution.
4. Memory Location: RAM
The following program illustrates the work of automatic variables.
void test();
void main()
{
test();
test();
test();
}
void test()
{
static int k=10;
printf(“%d\n”,k);
k++; }
Output:
10
11
12
Register variable: (register)
Register variables inform the compiler to store the variable in CPU register instead
of memory. Register variables have faster accessibility than a normal variable.
Generally, the frequently used variables are kept in registers.
But only a few variables can be placed inside registers. One application of register
storage class can be in using loops, where the variable gets used a number of times
in the program, in a very short span of time.
NOTE: We can never get the address of such variables.

SIVA SIVNI DEGREE COLLEGE 161 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Syntax to declare register variable is:
register datatype variablename;
register int rno;
register float price;
1. Scope: Local to the function in which it is declared.
2. Default initial value: Any random value i.e garbage value
3. Lifetime: Till the end of function/method block, in which the variable is defined.
4. Memory location: CPU registers
Example:
int main()
{
register int a;
for(a=0;i<50000;i++)
printf(“%d\t”,a);
return 0;
}
Note: Even though we have declared the storage class of our variable number as
register, we cannot surely say that the value of the variable would be stored in a
register. This is because the number of registers in a CPU is limited. In such scenario,
the variable works as if its storage class is auto.
Which storage class should be used and when
To improve the speed of execution of the program and to carefully use the memory
space occupied by the variables, following points should be kept in mind while using
storage classes:
 We should use static storage class only when we want the value of the variable to
remain same every time we call it using different function calls.
 We should use register storage class only for those variables that are used in our
program very oftenly. CPU registers are limited and thus should be used carefully.
 We should use external or global storage class only for those variables that are
being used by almost all the functions in the program.
 If we do not have the purpose of any of the above mentioned storage classes, then
we should use the automatic storage class.
Explain the concept of Inline funtion
The inline function can be substituted at the place where the function call is
happening. Function substitution is always compiler choice.
 In an inline function, a function call is replaced by the actual program code.
 Most of the Inline functions are used for small computations. They are not
suitable for large computing.
 An inline function is similar to a normal function. The only difference is that
we place a keyword inline before the function name.
Inline functions are created with the following syntax −
inline function_name ()
{
//function definition
}

SIVA SIVNI DEGREE COLLEGE 162 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Example
Following is the C program for inline functions −
#include<stdio.h>
inline int mul(int a, int b) //inline function declaration
{
return(a*b);
}
int main(){
int c;
c=mul(2,3);
printf("Multiplication:%d\n",c);
return 0;
}
Output
When the above program is executed, it produces the following result −
6
EXPLAIN IN DETAILED RECURSION IN C
 Recursion is a process in which a problem is defined in terms of itself. In ‘C’ it is
possible to call a function from itself. Functions that call themselves are known as
recursive functions, i.e. a statement within the body of a function calls the same
function. Recursion is often termed as ‘Circular Definition’. Thus recursion is the
process of defining something in terms of itself. To implement recursion technique
in programming, a function should be capable of calling itself.
 recursive function is one that calls itself directly or indirectly to solve a smaller
version of its task until a final call which does not require a self-call.
 Recursion is like a top–down approach to problem solving; it divides the problem
into pieces or selects one key step, postponing the rest.
 Iteration is more of a bottom–up approach; it begins with what is known and then
constructs the solution step by step.
The recursive algorithms will generally consist of an if statement with the
following form:
if (this is a base case)
then solve it directly
else
redefine the problem using recursion.

How to write a Recursive Function?


Before writing a recursive function for a problem its necessary to define the solution
of the problem in terms of a similar type of a smaller problem.

SIVA SIVNI DEGREE COLLEGE 163 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Two main steps in writing recursive function are as follows:
(i).Identify the Non-Recursive part(base case) of the problem and its solution(Part of
the problem whose solution can be achieved without recursion).
(ii).Identify the Recursive part(general case) of the problem(Part of the problem
where recursive call will be made).
Identification of Non-Recursive part of the problem is mandatory because without it
the function will keep on calling itself resulting in infinite recursion.
Every recursive solution has two major cases.
They are
 Base case, in which the problem is simple enough to be solved directly without making
any further calls to the same function.
 Recursive case, in which first the problem at hand is divided into simpler sub-parts.
Second the function calls itself but with sub-parts of the problem obtained in the first
step. Third, the result is obtained by combining the solutions of simpler sub-parts.
Write a program to calculate the factorial of a given number.
int Fact(int);
int main () {
int num, val;
printf ("\n Enter the number: ");scanf("%d", &num);
val = Fact (num);
printf ("\n Factorial of %d = %d", num, val);return 0;
}
int Fact (int n)
{
if (n==1)
return 1;
else
return (n * Fact(n–1));
}
Output
Enter the number: 5 Factorial of 5 = 120

Explain Indirect and Direct Recursion


If a function fun1() calls another function fun2() and the function fun2() in turn calls
function fun1(), then this type of recursion is said to be indirect recursion, because
the function fun1() is calling itself indirectly.

SIVA SIVNI DEGREE COLLEGE 164 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM

The chain of functions in indirect recursion may involve any number of functions.For
example suppose n number of functions are present starting from f1() to fn() and they
are involved as following: f1() calls f2(), f2() calls f3(), f3() calls f4() and so on with fn()
calls f1().
If a function calls itself directly i.e. function fun1() is called inside its own function
body, then that recursion is called as direct recursion.

Call by value Call by reference


A copy of value is passed tothe An address of value is passed tothe
function function
Changes made inside thefunction is Changes made inside the functionis
not reflected on other functions reflected outside the function also

Actual and formal arguments will Actual and formal arguments willbe
be created in different memory created in same memory location
location

Recursion Iteration
Repetitive execution of afunction Repetitive execution of one ormore
until stopping Condition is met, is statements is called Iteration, commonly
calledrecursion. known asloop.
Recursion is like a top-down Iteration is more of a bottom-upapproach
approach to problem solving asit as it begins with what is known and from
divides the problem into Pieces or this constructs the solution step by step.
selects one key step,postponing the
rest.

SIVA SIVNI DEGREE COLLEGE 165 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
POINTER
Define pointer expain the concept of declaring and initializing of pointer
variable
Pointer is a variable which holds the memory address of another variable. Pointers
are represented by '*'. It is a derive data type in C. Pointer returns the value of stored
address.
A pointer is a variable that contains the address of a variable the pointer does not
hold a value in the traditional sense; instead, it holds the address of another variable.
a pointer holds an address rather than a value, it has two parts.
The pointer itself holds the address.
The address points to a value.
C uses pointers in three mainways.
(i) Pointers in C provide an alternative means of accessing information stored in
arrays, which is especially valuable when working with strings. There is an intimate
link between arrays and pointers in C.
(ii) C uses pointers to handle variable parameters passed to functions.
(iii) They are used to create dynamic data structures, that are built up from blocks of
memory allocated from the heap at run time. This is only visible through the use of
pointers.
Syntax: <data_type> *pointer_name;
int *rno;
In above syntax,
pointer_name is a rno( variable).
pointer_name requires memory location of 2bytes
pointer_name points to a variable of the same type of data type.

Ex:
Int *ip;
double *dp;
float *fp;
char *ch ;
Address of Operator (&)
The Address Operator in C also called a pointer. This address operator is denoted by
“&”. This & symbol is called an ampersand. This & is used in a unary operator. The
purpose of this address operator or pointer is used to return the address of the
variable.
Once we declared a pointer variable, we have to initialize the pointer with a valid
memory address; to get the memory address of the variable ampersand is used.

SIVA SIVNI DEGREE COLLEGE 166 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
When we use the ampersand symbol as a prefix to the variable name & and it gives
the address of that variable. An address of the operator is used within C that is
returned to the memory address of a variable.
These addresses returned by the address of the operator are known as pointers
because they “point” to the variable in memory.
Usage:
While scanning the user input we used ampersand operator.
While displaying the address of the variable we used ampersand operator.
Address operators commonly used for 2 purposes:
 Conduct parameter passing by reference such as name.
 Establish pointer values and address of operator’s point to the memory location
because the value of the pointer is the memory location or memory address. The
data item saved in memory.
How does Address Operator work in C?
The address operator is working for returns the memory address of a variable. These
addresses are returned by the address of the operator are known as pointers because
they point to the variable in memory.
 Scanning the user input
scanf("%d",&variable_name); //stores the value of the variable
 Displaying the address of the variable
int a=10;
int address=&a;
Value of Operator (*)
The * is a unary operator which returns the value of object pointer by a pointer
variable. It is known as value of operator. It is also used for declaring pointer
variable.
For Example int A = 100;
int *ptr = &A;
In the first statement, we first declare an integer variable and initialize it with value
100. In next statement, we are declaring a pointer to a variable of type int and
initializing it with address of A.
Examples to Implement Address Operator in C
Scanning user integer input and display with the ampersand
//include is used to add basic C libraries
#include <stdio.h>
//main method is used to run C application
int main(void) {
int first_number, second_number; //declaring 2 variables
//Asking user to enter integer input
printf("Please enter any 2 integer number \n");
//store the number with ampersand symbol
scanf("%d\n%d",&first_number,&second_number);
printf("User enter numbers %d and %d ", first_number, second_number);
return 0;
}
Output:
Please enter any 2 integer number
10
20
User enter numbers 10 20

SIVA SIVNI DEGREE COLLEGE 167 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Explain the process of Pointer memory allocation
Pointer initialization: When declaring pointers we may want to explicitly specify
which variable we want them to point to:
int i=3;
int *j;
int j=&i;
When a pointer initialization takes place we are always assigning the reference
value to where the pointer points (b), never the value being pointed (*b). You must
consider that at the moment of declaring a pointer, the asterisk (*) indicates only
that it is a pointer, it is not the dereference operator (although both use the same
sign: *). Remember, they are two different functions of one sign.
int a=10;
int *b;
b = & a; i.e a is equal *b that is 10 same b is equal to address of a
Pointers to pointers:
C++ allows the use of pointers that point to pointers, that these, in its turn, point to
data (or even to other pointers). In order to do that, we only need to add an asterisk
(*) for each level of reference in their declarations:
char a;
char * b;
char ** c;
a = 'z';
b = &a;
c = &b;
This, supposing the randomly chosen memory locations for each variable of 7230,
8092 and 10502, could be represented as:

The value of each variable is written inside each cell. Under the cells are their
respective addresses in memory.
The new thing in this example is variable c, which can be used in three different
levels of indirection, each one of them would correspond to a different value:
c has type char** and a value of 8092
*c has type char* and a value of 7230
**c has type char and a value of 'z'
Features of Pointer :
 Pointer variable should have prefix '*'.
 Combination of data types is not allowed.
 Pointers are more effective and useful in handling arrays.
 It can also be used to return multiple values from a function using function
arguments.
 It supports dynamic memory management.
 It reduces complexity and length of a program.
 It helps to improve execution speed that results in reducing program execution
time.Alternative way to access array elements information.
 Every pointer variable will address only two bytes of memory occupy.

SIVA SIVNI DEGREE COLLEGE 168 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
/* Program to demonstrate pointer. */
#include <stdio.h>
#include <conio.h>
void main() {
int a=10;
int *ptr;
clrscr();
ptr = &a;
printf("\n\t Value of a : %d", a);
scanf("\n\n\t Value of pointer ptr : %d", *ptr);
printf("\n\n\t Address of pointer ptr : %d", ptr);
getch();}
Consider the following program.
#include <stdio.h>
int main()
{
int *p;
float *q;
double *r;
printf(“\n the size of integer pointer is %d”,
sizeof(p));
printf(“\n the size of float pointer is %d”,
sizeof(q));
printf(“\n the size of double pointer is %d”,
sizeof(r));
printf(“\n the size of character pointer is %d”,
sizeof(char *));
return 0; }
Output
In Turbo C
the size of integer pointer is 2
the size of float pointer is 2
the size of double pointer is 2
the size of character pointer is 2

Printing pointer value


A pointer variable contains a memory address that points to another variable. To
print the memory address stored in pointers and non-pointer variables using the %p
conversion specifier and to learn the use of the %p conversion specifier, study the
following program.
#include <stdio.h>
int main(void)
{
int a=10, *p;
p=&a;
printf(“\n p = %p”, p);
return 0;
}
Output
p = 0022FF2C

SIVA SIVNI DEGREE COLLEGE 169 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
What is NULL pointer in C
NULL pointer in C is a pointer which is pointing to nothing. It is used to initialize a
pointer at the time of declaration if we don't have any explicit value to initialize. It is
a good practice to initialize a pointer with NULL to ensure that it is not pointing to a
random memory location. The NULL is a macro constant with a value of zero defined
in various C header files like stdio.h, stdlib.h, alloc.h etc.
A pointer initialized with NULL is known as NULL pointer.
int *ptr = NULL;
Pointer ptr is initialized with NULL. Pointer ptr is not pointing to any valid
memory location. We can check whether a pointer is a NULL pointer or not as
follows:
if(ptr == NULL)
if(!ptr)
What are the advantages of using Pointers in C
 We can dynamically allocate or deallocate space in memory at run time by using
pointers.
 Using pointers we can return multiple values from a function.
 We can pass arrays to a function as call by Reference.
 Pointers are used to efficiently access array elements, as array elements are stored
in adjacent memory locations. If we have a pointer pointing to a particular element
of array, then we can get the address of next element by simply incrementing the
pointer.
 Pointers are used to efficiently implement dynamic Data Structures like Queues,
Stacks, Linked Lists, Tress etc.
 The use of pointers results into faster execution of program.
void Pointer
A void pointer is a special type of pointer. It can point to any data type, from an
integer value or a float to a string of characters. Its sole limitation is that the pointed
data cannot be referenced directly (the asterisk * operator cannot be used on them)
since its length is always undetermined. Therefore, type casting or assignment must
be used to turn the void pointer to a pointer of a concrete data type to which we can
refer.
#include <stdio.h>
int main(){
int a=5,
double b=3.1415;
void *vp;
vp=&a;
printf(“\n a= %d”, *((int *)vp));
vp=&b;
printf(“\n a= %d”, *((double *)vp));
return 0;}
Output
a= 5
b= 3.141500
Note: Void pointer can point to a variable of any data type, from an integer value
or a float to a string of characters.
 The type casting or assignment must be used to turn the void pointer to a pointer
of a concrete data type to which we can refer.

SIVA SIVNI DEGREE COLLEGE 170 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Arrays and Pointers
Pointers and arrays are inseparably related, but they are not synonymous.
One-dimensional Arrays and Pointers
An array is a non-empty set of sequentially indexed elements having the same type
of data. Each element of an array has a unique identifying index number. Changes
made to one element of an array does not affect the other elements. An array
occupies a contiguous block of memory. The array a is laid out in memory as a
contiguous block, as shown in Fig.

Elements of array are stored in the successive increasing locations of memory. For
example, if the array starts at memory location 2147478270 (considering a 32-bit
machine), then with the assumed size of an integer as four bytes, the first element is
stored at location 2147478270, the second element at location 2147478274, and so on.
Here, the locations are taken as arbitrary.
Array notation is a form of pointer notation. The name of an array is the beginning
address of the array, called the base address of the array., that is, the base address of
an array is the address of the zeroth element of the array.
The array name is referred to as an address constant. Mentioning the name of the
array fetches its base address. Consider the following
program.
Example
2. (a) #include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u %u”, array, &array[0]);
return 0;
}
Output
2147478270 2147478270
Again, consider the following program.
(b) #include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u %u”, array, &array);
return 0;
}
Output
2147478270 2147478270
Note
 Array name is a pointer constant. It cannot be used as lvalue, that, is array names
cannot be used as variables on the left of an assignment operator.
 Both array and &array would give the base address of the array, but the only
difference is under ANSI/ISO Standard C, &array yields a pointer, of type pointer-
to array of-the data type to the entire array.

SIVA SIVNI DEGREE COLLEGE 171 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
(a) int main()
{
int a[]={10, 20, 30, 40, 50};
int i;
for(i=0;i<5;++i)
printf(“\n%d”, a[i]);
return 0;
}
Output
10
20
30
40
50
(b) #include <stdio.h>
int main()
{
int a[]={10, 20, 30, 40, 50};
int i;
for(i=0;i<5;++i)
printf(“\n%d”, *(a+i));
return 0;
}
Output
10
20
30
40
50
Pointers and Strings
Strings are one-dimensional arrays of type char. By convention, a string in C is
terminated by the end-of-string sentinel \0, or null character. The null character is a
byte with all bits off; hence, its decimal value is zero. It is useful to think of strings
as having a variable length, delimited by \0, but with the maximum length
determined by the size of the string.
The size of a string must include the storage needed for the end-of-string sentinel.
As with all arrays, it is the job of the programmer to make sure that string bounds
are not overrun. String constants are written between double quotes.
For example, “abc” is a character array of size 4, with the last element being the null
character \0. Note that string constants are different from character constants. For
example, “a” and ‘a’ are not the same. The array “a” has two elements, the first
with value ‘a’ and the second with value ‘\0’.
A string constant, like an array name by itself, is treated by the compiler as a pointer.
Its value is the base address of the string. Like the numeric array, individual
characters contained in a string can be printed.

SIVA SIVNI DEGREE COLLEGE 172 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
int main()
{
char s[]=“Oxford”;
for(i=0;s[i]!=‘\0’;++i)
putchar(s[i]);
return 0;
}
 A string in C is a pointer itself.
The following program proves the fact.
int main()
{
for(i=0;*(“I am a pointer” + i)!=‘\0’;++i)
printf(“%c”,*(“I am a pointer” + i));
return 0;
}
Output
I am a pointer
Pointer to Pointer in C
A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
Normally, a pointer contains the address of a variable. When we define a pointer to
a pointer, the first pointer contains the address of the second pointer, which points to
the location that contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by


placing an additional asterisk in front of its name.
For example, the following declaration declares a pointer to a pointer of type int −
int **var;
Consider the following declaration.
int a=5;
int *p; ¨ pointer to an integer
int **q; ¨ pointer to a pointer to an integer
p=&a;
q=&p;
 To refer to a using pointer p, dereference it once, that is, *p.
 To refer to a using q, dereference it twice because there are two levels of
indirection involved.
 If q is dereferenced once, actually p is referenced which is a pointer to an integer.
It may be represented diagrammatically as follows
So, *p and **q print 5 if they are printed with a printf statement.
int main(){
int a=5;
int *p,**q;
p=&a;
q=&p;
printf(“\n *p=%d”,*p);
printf(“\n **q=%d”,**q);
return 0;}

SIVA SIVNI DEGREE COLLEGE 173 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
When a target value is indirectly pointed to by a pointer to a pointer, accessing that
value requires that the asterisk operator be applied twice, as is shown below in the
example −
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Explain about Array of Pointers
There may be a situation when we want to maintain an array, which can store
pointers to an int or char or any other data type available.
Syntax to declare pointer to an array is
datatype (*pointer_variable)[size];
For example:
int (*ptr)[10]; ,Here ptr is a pointer that can point to an array of 10 integers, where we
can initialize ptr with the base address of the array then by incre menting the value
of ptr we can access different elements of array a[].
Following is the declaration of an array of pointers to an integer −
For Ex2:
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds
a pointer to an int value.
An array of pointers can be declared very easily. It is done thus.
int *p[10];
This declares an array of 10 pointers, each of which points to an integer. The first
pointer is called p[0], the second is p[1], and so on up to p[9]. These start off as
uninitialized—
they point to some unknown point in memory. We could make them point to integer
variables in memory as follows.
int* p[10];
int a = 10, b = 20, c = 30;
p[0] = &a;
p[1] = &b;
p[2] = &c;

SIVA SIVNI DEGREE COLLEGE 174 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
It can be seen from the diagram that there is no way of knowing in advance where
the compiler will place these numbers in memory. They may not even be stored in
order

The obvious thing to do is to sort the numbers in memory, not by moving the
numbers themselves around but by altering the order of the pointers to them
The following example uses three integers, which are stored in an array of pointers,
as follows −
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Another Example:
int main() {
int a[3][3]={1,2,3,4,5,6,7,8,9};
int *ptr[3]={a[0],a[1],a[2]};
int i;
for(i=0;i<3;++i)
printf(“%d”,*ptr[i]);
printf(“\n”);
for(i=0;i<3;++i)
printf(“%d”,*a[i]);
return 0;}
Output
147
147

Explain the concept of Pointer to Array


Suppose we have an array of unsigned long values called v. We can declare a
pointer to a simple integer value and make it point to the array as is done normally.
int v[5] = {1004, 2201, 3000, 432, 500};
int *p = v;
printf(“%d \n”, *p);

SIVA SIVNI DEGREE COLLEGE 175 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
This piece of code displays the number, which the pointer p points to, that is, the
first number in the array, namely 1004.

C tends to treat arrays almost as though they were pointers, which is why we can set
a pointer to an array straight rather than using the address of operator. The
instruction p  =  v makes the pointer point to the address of the array. The number at
this address is the first element of the array; so that is the value produced when we
access *p.
p++ gives some extra arithmetic instructions that let us use the pointer to the array
more flexibly.
p++
This instruction increases the pointer so that it points to the next element of the array.
If it is followed by the instruction printf(“%d \n”, *p); then it would display the
number 2201, which is the content of element v[1] (i.e., the second element).
int main() {
int a[2][3]={{3,4,5},{6,7,8}};
int i; int(*pa)[3];
pa=a;
for(i=0;i<3;++i)
printf(“%d\t”,(*pa)[i]);
printf(“\n”);
pa++;
for(i=0;i<3;++i)
printf(“%d\t”,(*pa)[i]);
return 0; }
Output
345
678
Difference between an array of pointers and a pointer to an array

Explain in detailed Dynamic Memory Allocation in c


The concept of dynamic memory allocation in c language enables the C
programmer to allocate memory at runtime.
Dynamic memory allocation is a way to defer the decision of how much memory
is necessary until the program is actually running, or give back memory that the
program no longer needs.
The area from where the application gets dynamic memory is called heap. The heap
starts at the end of the data segment and grows against the bottom of the stack. If
both meet, the program is in trouble and will be terminated by the operating
system. Thus, C gives programmers the standard sort of facilities to allocate and de-
allocate dynamic heap memory.
SIVA SIVNI DEGREE COLLEGE 176 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
There are two types of available memories- stack and heap. Static memory
allocation can only be done on stack whereas dynamic memory allocation can be
done on both stack and heap. An example of dynamic allocation to be done on the
stack is recursion where the functions are put into call stack in order of their
occurrence and popped off one by one on reaching the base case.
Reasons and Advantage of allocating memory dynamically:
 When we do not know how much amount of memory would be needed for the
program beforehand.
 When we want data structures without any upper limit of memory space.
 When you want to use your memory space more efficiently.
Example: If you have allocated memory space for a 1D array as array[20] and you
end up using only 10 memory spaces then the remaining 10 memory spaces would
be wasted and this wasted memory cannot even be utilized by other program
variables.
 Dynamically created lists insertions and deletions can be done very easily just by
the manipulation of addresses whereas in case of statically allocated memory
insertions and deletions lead to more movements and wastage of memory.
 When you want you to use the concept of structures and linked list in programming,
dynamic memory allocation is a must.
let's understand the difference between static memory allocation and dynamic
memory allocation.
Static memory allocation The compiler allocates the required memory space for a
declared variable. By using the address of operator, the reserved address is
obtained that may be assigned to a pointer variable. Since most declared variables
have static memory, this way of assigning pointer value to a pointer variable is
known as static memory allocation.
Dynamic memory allocation A dynamic memory allocation uses functions such as
malloc() or calloc() to get memory dynamically. If these functions are used to get
memory dynamically and the values returned by these functions are assigned to
pointer variables, such assignments are known as dynamic memory allocation.
Memory is assigned during run-time.
C provides access to the heap features through library functions that any C code
can call. The prototypes for these functions are in the file <stdlib.h>.
The following functions are used in dynamic memory allocation and are defined
in <stdlib.h>
the methods used for dynamic memory allocation.
malloc() allocates single block of requested memory.
calloc() allocates multiple block of requested memory.
realloc() reallocates the memory occupied by malloc() or calloc() functions.
free() frees the dynamically allocated memory.
1. malloc()
Declaration: void*malloc(size_t size);
Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory.
And, the pointer ptr holds the address of the first byte in the allocated memory.
This function is used to allocate memory dynamically. The argument size specifies
the number of bytes to be allocated.
SIVA SIVNI DEGREE COLLEGE 177 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
On success, malloc() returns a pointer to the first byte vof allocated memory. The
returned pointer is of type void, which can be type cast to appropriate type of pointer.
The memory allocated by malloc() contains garbage value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
2. calloc()
Declaration: void*calloc(size_t n,size_t size);
Syntax:
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the
size of the float.

SIVA SIVNI DEGREE COLLEGE 178 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
This function is used to allocate multiple blocks of memory. The first argument
specifies the number of blocks and the second one specifies the size of each block.
The memory allocated by calloc() is initialized to zero.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
3. realloc()
Declaration: void*realloc(void *ptr,size_t newsize);
The function realloc() is used to change the size of the memory block. It alters the size
of the memory block without losing the old data. This function takes two arguments,
first is a pointer to the block of memory that was previously allocated by mallloc() or
calloc() and second one is the new size for that block.
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.

SIVA SIVNI DEGREE COLLEGE 179 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.\n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}

SIVA SIVNI DEGREE COLLEGE 180 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7,
4. free();
Declaration:
void free(void *p);
This function is used to release the memory space allocated dynamically. Rhe
memory released by free() is made available to the heap again and can be used for
some other purpose. We should not try to free any memory location that was not
allocated by malloc(), calloc() or realloc().
Syntax:
free(ptr);

IMPORTANT QUESTIONS
1. Define function? Need of the function and advantages of functions?
2. How functions are works:
3. Explain function elements with syntax
4. Explain the main categories of the user defined functions
5. Define actual arguments and formal arguments
6. Explain the concept of passing parameters to functions
7. Explain call by reference with example
8. Explain in detailed recursion in c
9. How to write a recursive function?
10. Explain indirect and direct recursion
11. Explain the concept of inline funtion
12. Explain briefly about storage classes in c
13. Which storage class should be used and when
14. Define scope rules
15. Define pointer features of pointer :
16. Expain the concept of declaring and initializing of pointer variable
17. Explain the process of pointer memory allocation
18. Explain the concept of pointers to pointers
19. How pointer is associated with functions
20. Explain passing array to function using call by reference
21. How to pass an entire array to a function as an argument?
22. Write about array of pointers
23. Write about pointer to a structure in c
24. Discuss about pointers and strings
25. Explain the concept of pointers to pointers
26. Explain the concept dynamic memory allocation with example

SIVA SIVNI DEGREE COLLEGE 181 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
UNIT-IV
User-defined Data Types and Variables
C provides facilities to construct user defined data types from the fundamental data
types. A user-defined data type may also be called a derived data type. The array
type is a derived data type that contains only one kind of fundamental data type
defined in C. This means that the array elements, represented by a single name,
contain homogeneous data.
Apart from the primary data type’s int, char, float C allows us to define our own data
types. This is done for the purpose of customized programming and to reduce the
complexity of programs.A user-defined data type may also be called a derived data
type.
In C user defined data types can be created in three different ways
 structures
 unions
 enumerations
STRUCTURE
INTRODUCTION
A Structure is a user defined data type that can store related information together.
The variable within a structure are of different data types and each has a name that
is used to select it from the structure. C arrays allow you to define type of variables
that can hold several data items of the same kind but structure is another user defined
data type available in C programming, which allows you to combine data items of
different kinds.
Structures are used to represent a record, Suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book:
• Title
• Author
• Subject
• Book ID
Defining a Structure
Keyword 'struct' is used to declare structure. The variables which are declared inside
the structure are called as 'members of structure'.
Structure is user defined data type which is used to store heterogeneous data under
unique name.
Structure is a way of defining the user defined data type that encapsulates the
different data types. Or group of different data types combined together into an
object is known as structure.
 Structure members can store in individual memory locations.
 Structure block can be terminated with semi-colon.
 To access the structure members we can use (.) dot operator with object.

Syntax:
struct structure_nm{
<data-type> element 1;
<data-type> element 2;
-----------
<data-type> element n;
}struct_var1.struct-var2;

SIVA SIVNI DEGREE COLLEGE 182 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
 structure_name is user defined structure name. We can give name as structure by
using the rules of identifier.
 Element1, element2 and so element n on are called members of the structure. Each
member is declared inside the structure independently using data type.
 The structure_variables are the list of variable names separated by commas.
 The structure_ variable is also known as an instance variable of the structure. Each
member_name declared within the braces is called a member or structure element.
 The structure definition should be terminated with a semicolon.
Example :
struct emp_info
{
char emp_id[10];
char nm[100];
float sal;
}emp;//structure variable
struct personal_data
{
char name[100];
char address[200];
int year_of_birth;
int month_of_birth;
int day_of_birth;
}raj,sai,gopi; //structure variables
How to declaring structure variables:
After defining a structure format, we can declare variables of that type. Structure
variables are declared in two ways.
At the time of structure definition (Along with structure definition)
After structure definition.
1. at the time of structure definition (Along with structure definition)
Structure variables are declared before closing the structure definition. i.e., before
closing semicolon (;).

2. After structure definition in main ()


Structure variables are declared after closing the structure definition. We can
declare like normal variable in the program. The keyword struct is used to define
variables of structure type.
Syntax: struct structure_name var1, var2…..;
Ex: struct student s1, s2 ;
Structure Initialization
Assigning constants to the members of the structure is called initializing of
structure.
Syntax:
struct struct_name
{
data _type member_name1;
data _type member_name2;
} struct_var={constant1,constant2};
Ex: emp={101,”sai”,25000};
SIVA SIVNI DEGREE COLLEGE 183 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Accessing members of Structure
To access any member of a structure, we use the member access operator or dot
operator (.). The member access operator is used between the structure variable and
the structure member that we wish to access.
The dot operator is used to select a particular member of the structure. To assign
value to the individual Data members of the structure variable.
Syntax: structure_var . member ;
Ex: s1. rno = 101;
We can also initialize the values to members of structure at the time of declaration
of structure variable.
struct student s={101,”kiran”,…..};
To input values for data members of the structure variable stud, can be written as,
scanf(“%d”,&stud.roll);
scanf(‘’%s”,&stud.name);
To print the values of structure variable stud, can be written as:
printf(“%s”,stud.roll);
printf(“%f”,stud.name);
initialization of Structure:
After declaration of the structure variable the memory will be allocated to members
of structure.The members of a structure are always stored in contiguous memory
locations. The size of structure variable is the sum of individual member memory.
Consider the following example:
struct book
{
char title[10];
int pages;
float price;
};
struct book b1={“BASIC”,360,172.00};
Here the structure variable b1 occupies 16 bytes (10+2+4=16) of memory space. The
storing of values in to members is shown below.

Write about arrays in structures:


We can declare an array with in the structure definition. Declaring an array
in structure definition is called Array in Structures. This array is also a member of
structure. It can be accessed as same as simple member of the structure.

SIVA SIVNI DEGREE COLLEGE 184 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
/* Program to demonstrate array in structures */
struct student
{
int rno, marks[6]; };
void main() {
struct student s ;
int i;
clrscr();
printf("\n Enter marks of Student :");
scanf(“%d”, &s.rno);
printf("\n Enter marks of Student :");
for(i=0;i<5;i++)
{
scanf(“%d”, &s.marks[i]);
}
printf(“\n Student R.No=%d”,s.rno);
printf("\n Marks of student:\n");
for(i=0;i<5;i++)
{
printf("\t %d ”, s.marks[i]);
}
getch(); }
/* Program to demonstrate array in structures */
struct student
{
int rno,marks[5],total;
float per;
char name[20]; };
void main() {
struct student s;
int i;
printf("\nEnter Roll No:");
scanf("%d",&s.rno);
printf("\nEnter Name:");
scanf("%s",&s.name);
printf("\nEnter Marks:");
for(i=0;i<5;i++)
scanf("%d",&s.marks[i]);
printf("\nRoll No: %d",s.rno);
printf("\nName :%s",s.name);
printf("\nSubject Marks");
s.total=0;
for(i=0;i<5;i++)
{
printf("\nsub %d \t %d",i+1,s.marks[i]);
s.total=s.total+s.marks[i];
}
s.per=s.total/5;
printf("\n Total= \t %d",s.total);
printf("\n Percentaage= %f",s.per);
getch(); }
SIVA SIVNI DEGREE COLLEGE 185 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Discuss about Array of Structures:
An array is a collection of similar data types. Similarly, we can also define an array
of structures. i.e., if we want to declare more structure variables, use array of structure
variables. This means that the structure variable would be an array of objects, each of
which contains the member elements declared within the structure construct.
This means that the structure variable would be an array of objects, each of which
contains the member elements declared within the structure construct. The general
construct for declaration of an array of structure is given as follows.
struct <structure_tag_name >
{
<data_type member_name1>;
<data_type member_name2>;
.. .
}<structure_variable>[index];
or
struct
<structure_tag_name><structure_variable>[index];
Ex:
struct marks
{
int sub1, sub2, sub3;
} s[10];
struct student s[10] ;

/* Program to demonstrate array of structures */


struct marks
{
int sub1, sub2, sub3;
};
void main()
{
struct marks s[5] ;
int i;
clrscr();
for(i=0;i<5;i++)
{
printf("\n Enter marks of Student %d :", i+1);
scanf("%d%d%d",&s[i].sub1,&s[i].sub2,&s[i].sub3);
}
printf("\n\n Marks of students:\n");
for(i=0;i< 5;i++)
{
printf("\nStudent %d Marks: ", i+1);
printf("\nSub1=%d \t Sub2=%d \t Sub3= %d ",s[i].sub1,s[i].sub2,s[i].sub3);
}
getch();
}

SIVA SIVNI DEGREE COLLEGE 186 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Define how structures can be nested
One structure can be nested within another structure. Using this facility complex data
types can be created.The structure that contains another structure as its members is
called a nested structure or a structure within a structure is called nested structure.
The structure should be declared separately and then be grouped into high level
structure.
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
<data-type> element n;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
<data-type> element n;
} inner_struct_var;
} outer_struct_var;

/* Program to demonstrate nesting of structures */


struct employee
{
char name[10];
struct address
{
char phone[10];
char city[10];
int pin;
}a;
};
void main()
{
struct employee e={"Arnav","6234560016","Dallas",4210};
clrscr();
printf("\nName-->%s\nPhone-->%s",e.name,e.a.phone);
printf("\nCity-->%s\nPincode-->%d",e.a.city,e.a.pin);
getch();
}

SIVA SIVNI DEGREE COLLEGE 187 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
How to copy structures into another structure
The values of a structure variable can be assigned to another structure variable of the
same type using the assignment operator.
A structure can be assigned to another structure of the same type.
* Program to demonstrate copying of structures *
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[10];
int age;
float salary;
};
void main()
{
struct employee e1={"Arnav",28,40000.00};
struct employee e2,e3;
clrscr();
strcpy(e2.name,e1.name);
e2.age=e1.age;
e2.salary=e1.salary;
e3=e2;
printf("\n%s\t%d\t%f",e1.name,e1.age,e1.salary);
printf("\n%s\t%d\t%f",e2.name,e2.age,e2.salary);
printf("\n%s\t%d\t%f",e3.name,e3.age,e3.salary);
getch();
}
Copying one structure to another of the same type.
#include <stdio.h>
struct employee
{
char grade;
int basic;
float allowance;
};

int main()
{
struct employee ramesh={‘b’, 6500, 812.5};
struct employee vivek;
vivek = ramesh; /* copy respective members of ramesh to vivek */
printf(“\n vivek’s grade is %c, basic is Rs %d, \allowance is Rs %f”,
vivek.grade,vivek.basic,\
vivek.allowance);
return 0;
}
O utput
vivek’s grade is b, basic is Rs 6500, allowance
is Rs 812.500000

SIVA SIVNI DEGREE COLLEGE 188 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
DISCUSS ABOUT PASSING STRUCTURES AS ARGUMENTS IN
FUNCTIONS
Like an ordinary variable, a structure variable can also be passed to a function. We
may either pass individual structure elements or the entire structure variable at one
go.
/* Program to demonstrate passing structures to functions */
#include<string.h>
struct record
{
char name[10];
int rollno;
float percent;
}r;
void main()
{
void display(struct record r);
clrscr();
strcpy(r.name,"Arnav");
r.rollno=20;
r.percent=92.0;
display(r);
getch();
}
void display(struct record r)
{
printf("\nSTUDENT RECORD");
printf("\nName:");
puts(r.name);
printf("Roll#:%d",r.rollno);
printf("\nPercentage:%f",r.percent);
}

KEY ARRAY STRUCTURE


Basic An array is a collection of A structure is a collection of
variables of same data variables of different data type.
type.
Syntax type array_name[size]; struct sruct_name{
type element1;
type element1;
.
.
} variable1, variable2, . .;

Memory Array elements are stored Structure elements may not be


in contiguous memory stored in a contiguous memory
location. location.

Access Array elements are Structure elements are accessed


accessed by their index by their names.
number.

SIVA SIVNI DEGREE COLLEGE 189 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Operator Array declaration and Structure element accessing
element accessing operator is "." (Dot operator).
operator is "[ ]" (square
bracket).
Pointer Array name points to the Structure name does not point to
first element in that array the first element in that structure
so, array name is a so, structure name is not a
pointer. pointer.

Objects Objects (instances) of an Structure objects (instance or


array cannot be created. structure variable) can be created.

Size Every element in array is Every element in a structure is of


of same size. different data type.

Bit filed Bit filed cannot be defined Bit field can be defined in a
in an array. structure.
Keyword There is no keyword to "struct" is a keyword used to
declare an array. declare the structure.

User-defined Arrays are not user- Structure is a user-defined


defined they are directly datatype.
declared.
Accessing Accessing array element Accessing a structure elements
requires less time. require comparatively more time.

Searching Searching an array Searching a structure element


element takes less time. takes comparatively more time
than an array element.

Discuss about structures and pointers


Declaring pointers to structures is basically the same as declaring a normal pointer.
A typical construct for declaring a pointer to a structure will appear as follows.
struct <structure_tag_name >
/* structure declaration */
{
<data_type member_name_1>; <data_type member_name_2>;
.
.
<data_type member_name_n>;
}*ptr;
or
struct <structure_tag_name>
{
<data_type member_name_1>; <data_type member_name_2>;
.
<data_type member_name_n>; };
struct <structure_tag_name> *ptr;
SIVA SIVNI DEGREE COLLEGE 190 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
This pointer, *ptr, can be assigned to any other pointer of the same type, and can be
used to access the members of its structure. To access the members within the
structure, the dot operator is used with the pointer variable.
For example, to enable the pointer variable to access the member member_ name_1,
the following construct is used.
(*ptr).member_name_1
The bracket is needed to avoid confusion about the ‘*’ and ‘.’ operators.
C includes a shorthand notation that does exactly the same thing.
ptr-> member_name_1
For initializing the structure members through a pointer to the structure, any one of
the following constructs is used.
(*ptr).member_name_x = constant;
or
ptr-> member_name_x = constant;
where x is 1 to N, and N is the total number of members in the structure.
The following example uses pointer to structure.
Write a program using a pointer to structure illustrating the initialization of the
members in the structure.
struct test1
/* declaration of structure “test” */
{
char a;
int i;
float f;
};
int main() {
struct test1 *pt; /* declaring pointer to the
structure */
clrscr();
pt->a=‘K’; /* initializing char a */
pt->i=15; /* initializing int i */
pt->f=27.89; /* initializing float f */
printf(“\n a=%c, i=%d, f=%f”,pt->a,pt->i,pt->f);
printf(“\n Enter new char, int, float:”);
scanf(“%c %d %f”,&pt->a,&pt->i,&pt->f);
/* input for members */
printf(“\n a=%c, i=%d, f=%f”,pt->a,pt->i,pt->f);
return 0; }
/* function to link-in floating
point emulator */
void linkfloat()
{
float a,*x;
x=&a;
a=*x;
}
Output
a=k, i=15, f=27.889999
Enter new char, int, float: d 45 67.53
a=d, i=45, f=67.529999

SIVA SIVNI DEGREE COLLEGE 191 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
UNION
Define union and explain creating declaring and initializing an union
A union is a structure, the members of which share the same storage. The amount of
storage allocated to a union is sufficient to hold its largest member. At any given time,
only one member of the union may actually reside in that storage.
The way in which a union’s storage is accessed depends on the member name that is
employed during the access. It is the programmer’s responsibility to keep track of
which member currently resides in a union.
A union is identified in C through the use of the keyword union in place of the
keyword struct. Virtually, all other methods for declaring and accessing unions are
identical to those for structures.
Unions provide an efficient way of using the same memory location for multiple-
purpose.
Union is similar to that of structure. Syntax of union is similar to structure. But the
major difference between structure and union is 'storage.' In structures, each member
has its own storage location, whereas all the members of union use the same location.
Union contains many members of different types; it can handle only one member at
a time.
To declare union data type, 'union' keyword is used.
Union holds value for one data type which requires larger storage among their
members.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
}union_variable;

Example:
union techno
{
int comp_id;
char nm;
float sal;
}tch;
In above example, it declares tch variable of type union. The union contains three
members as data type of int, char, float. We can use only one of them at a time.
Declaring Union Variables:
After defining a union format, we can declare variables of that type. Union
variables are declared in two ways.
At the time of Union definition (Along with union definition)
After union definition.
1. At the time of union definition (Along with union definition)
Union variables are declared before closing the union definition. i.e., before
closing semicolon(;).

SIVA SIVNI DEGREE COLLEGE 192 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
2. After union definition in main ()
Union variables are declared after closing the union definition. We can declare
like normal variable in the program. The keyword union is used to define variables
of union type.
Syntax: union union_name var1, var2…..;
Ex: union student s1, s2 ;
Accessing memebers of Union
To access any member of a union, we use the member access operator or dot
operator (.). The member access operator is used between the union variable and
the union member that we wish to access.
Syntax: union_var . member
Ex: s1. rno = 101;
initialization of union:
After declaration of the structure variable the memory will be allocated to members
of union.The members of a union are always stored in contiguous memory locations.
The size of union variable is the max data type of individual member memory.
Consider the following example:
union book
{
char title[10];
int pages;
float price;
};
struct book b1={“BASIC”,360,172.00};
Memory of Union variable:

After declaration of the union variable the memory will be allocated to only one
member of union. i.e., same memory location, can be used to store multiple types of
data.
The memory occupied by a union is the size (memory) of largest member of the
union.
Consider the following example:
union book
{
char title[20];
int pages;
float price;
} b;
Here the union variable b occupies 20 bytes of memory space because this is the
maximum space which can be occupied by a character string title.
Note: A union is a special data type available in C that enables you to store different
data types in the same memory location.

SIVA SIVNI DEGREE COLLEGE 193 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
/* Program to demonstrate union. */
union techno
{
int id;
char nm[50];
}tech;
void main()
{
clrscr();
printf("\n\t Enter developer id : ");
scanf("%d", &tech.id);
printf("\n\n\t Enter developer name : ");
scanf("%s", tech.nm);
printf("\n\n Developer ID : %d", tech.id);//Garbage
printf("\n\n Developed By : %s", tech.nm);
getch();
}
Output :
Enter developer id : 101
Enter developer name : Chandra
Developer ID : 25972
Developed By : Chandra
Structure Union
1.The keyword struct is used to define 1. The keyword union is used to
a structure define a union.
2. When a variable is associated with a 2. When a variable is associated with a
structure, the compiler allocates the union, the compiler allocates the
memory for each member. The size of memory by considering the size of the
structure is greater than or equal to the largest memory. So, size of union is
sum of sizes of its members. The equal to the size of largest member.
smaller members may end with unused
slack bytes.
3. Each member within a structure is 3. Memory allocated is shared by
assigned unique storage area of individual members of union.
location.
4. The address of each member will be 4. The address is same for all the
in ascending order This indicates that members of a union. This indicates
memory for each member will start at that every member begins at the same
different offset values. offset value.
5 Altering the value of a member will 5. Altering the value of any of the
not affect other members of the member will alter other member
structure. values.
6. Individual member can be accessed 6. Only one member can be accessed
at a time at a time.
7. Several members of a structure can 7. Only the first member of a union
initialize at once. can be initialized.

SIVA SIVNI DEGREE COLLEGE 194 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Discuss about Array of union:
An array is a collection of similar data types. Similarly, we can also define an array
of union. i.e., if we want to declare more union variables, use array of union variables.
This means that the union variable would be an array of objects, each of which
contains the member elements declared within the union construct.
The general construct for declaration of an array of structure is given as follows.
union <union_tag_name >
{
<data_type member_name1>;
<data_type member_name2>;
.. .
}<union_variable>[index];
or
struct <union_tag_name><union_variable>[index];
Ex:
struct marks
{
int sub1, sub2, sub3;
} s[10];
struct student s[10] ;

/* Program to demonstrate array of unions */


union marks
{
int sub1, sub2, sub3;
};
void main()
{
union marks s[5] ;
int i;
clrscr();
for(i=0;i<5;i++)
{
printf("\n Enter marks of Student %d :", i+1);
scanf("%d%d%d",&s[i].sub1,&s[i].sub2,&s[i].sub3);
}
printf("\n\n Marks of students:\n");
for(i=0;i< 5;i++)
{
printf("\nStudent %d Marks: ", i+1);
printf("\nSub1=%d \t Sub2=%d \t Sub3= %d ",s[i].sub1,s[i].sub2,s[i].sub3);
}
getch();
}
Structure versus Union
Memory allocation The amount of memory required to store a structure is the sum
of the size of all the members in addition to the slack bytes or padding bytes that
may be provided by the compiler. On the other hand, in case of a union, the amount
of the memory required is same as that of the largest member.

SIVA SIVNI DEGREE COLLEGE 195 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
This can be proved by the following program.
#include <stdlib.h>
#include <string.h>
struct S
{
int i;
char ch;
double d;
};
union U
{
int i;
char ch;
double d;
};
int main() {
printf(“\n Size of the structure is %d”, sizeof\
(struct S));
printf(“\n Size of the union is %d”, sizeof(union U));
return 0; }
Output
Size of the structure is 16
Size of the union is 8
Member access While all structure members can be accessed at any point of time,
only one member of a union can be accessed at any given time. Because at a
particular moment of time, only one union member will have a meaningful value.
The other members have garbage values.
It is the responsibility of the programmer to keep track of the active member.
Consider the following program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct S
{
int i;
char ch;
double d;
};
union U
{
int i;
char ch;
double d;
};

SIVA SIVNI DEGREE COLLEGE 196 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
int main()
{
struct S a={10,‘A’,3.1415};
union U b={10};
printf(“\n a.i=%d a.ch=%c a.d=%lf”,a.i,a.ch,a.d);
printf(“\n b.i=%d b.ch=%c b.d=%lf”,b.i,b.ch,b.d);
b.ch=‘B’;
printf(“\n b.i=%d b.ch=%c b.d=%lf”,b.i,b.ch,b.d);
b.d=5.12345;
printf(“\n b.i=%d b.ch=%c b.d=%lf”,b.i,b.ch,b.d);
return 0;
}
Output
a.i=10 a.ch=A a.d=3.141500
b.i=10 b.ch=
b.d=0.000000
b.i=66 b.ch=B b.d=0.000000
b.i=-1388133430 b.ch= b.d=5.123450
Identifying active members There is no way to find which of the members is active
at any instant of time. The program must keep track of active members explicitly.
Do’s and don’ts for unions
It is important to remember which union member is being used. If the user fills in a
member of one type and then tries to use a different type, the results can be
unpredictable. The following operations on union variables are valid.
 A union variable can be assigned to another union variable.
 A union variable can be passed to a function as a parameter.
 The address of a union variable can be extracted by using & operator.
 A function can accept and return a union or a pointer to a union.
 Do not try to initialize more than the one union member.
 Do not forget that the size of a union is equal to its largest member.
 Do not perform arithmetical or logical operations on union variables.
How Pointer Is used in a union
We have already learned that a pointer is a variable which points to the address of
another variable of any data type like int, char, float etc. Similarly, we can have a
pointer to structures, where a pointer variable can point to the address of a structure
variable. Here is how we can declare a pointer to a structure variable.
union student
{
char name[10];
char group[10];
int age;
}s1;

// declaring a pointer to a structure of type union student


union student *ptr;
This declares a pointer ptr that can store the address of the variable of type union
student. We can now assign the address of variable s1 to ptr using & operator.
1 ptr = &s1;
Now ptr points to the structure variable s1.

SIVA SIVNI DEGREE COLLEGE 197 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
How to Access members using Pointer
There are two ways of accessing members of union using pointer:
Using indirection (*) operator and dot (.) operator.
Using arrow (->) operator or membership operator.
Using Indirection (*) Operator and Dot (.) Operator
At this point ptr points to the structure variable s1, so by dereferencing it we will get
the contents of the s1. This means s1 and *ptr are functionally equivalent. To access a
member of structure write *ptr followed by a dot(.) operator, followed by the name
of the member.
For example:
*ptr.name – refers to the name of student
*ptr.group – refers to the group of student
Using arrow operator (->)
C provides another way to access members using the arrow (->) operator. To access
members using arrow (->) operator write pointer variable followed by -> operator,
followed by name of the member.
1 ptr ->name - refers to the name of student
2 ptr->group - refers to the group of student
The following program demonstrates how we can use a pointer to union.
#include<stdio.h>
union student
{
char name[10];
char group[10];
int age;
};
int main()
{
union student my_student = {"kumar", "Bsc", 25};
struct student *ptr_student;
ptr_student = &my_student;
printf("Student's name: %s\n", ptr_student->name);
printf("Student's group: %s\n", ptr_student->group);
printf("student age: %d\n", ptr_student ->age);
// changing the name of student from kumar to rajesh
strcpy(ptr_student ->name, "rajesh");
// increasing age of student by 5 year
ptr_student ->age++;
printf("student's new name is: %s\n", ptr_student ->name);
printf("student's age is: %d\n", ptr_student ->age);
return 0;
}
Enumeration Types
Define Enumarator
Enumeration data types are data items whose values may be any member of a
symbolically declared set of values. The symbolically declared members are integer
constants. The keyword enum is used to declare an enumeration type.
The general construct used to declare anenumeration type is
enum tag_name{member1, member2,…, memberN}
variable1,...,variableX;

SIVA SIVNI DEGREE COLLEGE 198 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
In this declaration, either tag_name or variable name may be omitted or both may be
present. But, at least one of them must exist in this declaration construct.
The enum tag_name specifies the user-defined type. The members are integer
constants.
By default, the first member, that is, member1, is given the value 0.
The second member,member2, is given the value 1. Members within the braces may
be initialized, in which case, the next member is given a value which is one more than
the preceding member.
So, each member is given the value of the previous member plus 1.
The general form of the construct for declaring variables of enum type separately is
enum tag_name variable1,...,variableX;
The variables can take on as values only the members in the member list. Therefore,
variable1 = member2;
assigns the value represented by member2 to variable1.
A typical declaration would be
enum days {Mon, Tues, Wed, Thurs, Fri, Sat, Sun};
The above declaration means that the values ‘Mon,...,Sun’ may be assigned to a
variable of type enum days. The actual values are 0,...,6 in this example and it is these
values that must be associated with any input or output operations.
The following example illustrates these features.
Write a program to illustrate the assignment of default values to the members of
data type enum.
#include <stdio.h>
enum days{Mon, Tues, Wed, Thurs, Fri, Sat, Sun };
int main()
{
enum days start, end;
start= Tues; /* means start=1 */
end= Sat; /* means end=5 */
printf(“\n start = %d, end = %d”, start,end);
start= 64;
printf(“\n start now is equal to %d”, start);
return 0;
}
Output
start = 1, end = 5
start now is equal to 64
Example of enumerated type
#include<stdio.h>
enum week{sunday,monday,tuesday,wednesday,thursday,friday,saturday};
void main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
}
Output : 4 day

SIVA SIVNI DEGREE COLLEGE 199 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Example:
main( )
{
enum colors {red=10,green=20,blue=30};
enum colors c1,c2;
c1=red;
c2=blue;
printf(‘’%d’’,c1); prints 10
printf(‘’%d’’,c2); prints 30
getch();}
write a c program to find the no. of days in a month using enum rated data type?
Solution:
#include<stdio.h>
#include<conio.h>
main( )
{
enum months{jan=31,feb=28,mar=31,apr=30,may=31,jun=30,jul=31,aug=31,
sep=30,oct=31,nov=30,dec=31};
enum months m1,m2;
m1=apr;
m2=sep;
printf(“\n days in apr=%d”,m1);
printf(“\n days in sep=%d”,m2);
getch( );
}

EXPLAIN FILES IN C IN DETAILED


A File is a collection of data stored on a secondary storage device like hard disk. File
operation is to combine all the input data into a file and then to operate through the
C program.
A file is a repository of data that is stored in a permanent storage media, mainly in
secondary memory
Various operations like insertion, deletion, opening closing etc can be done upon a
file. When the program is terminated, the entire data is lost in C programming. If you
want to keep large volume of data, it is time consuming to enter the entire data. But,
if file is created these information can be accessed using few commands.
Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents
of the file using a few commands in C.
You can easily move your data from one computer to another without any changes.
There are large numbers of functions to handle file I/O in C language. High level file
I/O functions can be categorized as:

1. Text file
2. Binary file

SIVA SIVNI DEGREE COLLEGE 200 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Explain text file in c
Text files contain ASCII codes of digits, alphabetic and symbols.
These files contain plain text which is easily editable, readable and deleteable content.
These files are less secure and takes more space as compare to binary file.
These files have extension .txt and can be created easily with any text editor.
It can be thought of as a stream of characters that can be processed sequentially. It
can only be processed (logically) in the forward direction. For this reason, a text file
is usually opened for only one kind of operation, that is, reading or writing or
appending, at any given time. Similarly, since text files only process characters, they
can only read or write one character at a time. Functions are provided that deal with
lines of text, but these still essentially process one character at a time.
As text streams are associated with text files, they may contain a sequence of lines.
Each line contains zero or more characters and ends with one or more characters that
specifythe end of the line.
When text data files are used, there are two representations of data—internal and
external. For example, a value of type int will usually be represented internally as two-
or four-bytes (16- or 32-bit) of memory. Externally, though, that integer will be
represented as a string of characters representing its decimal or hexadecimal value.
Conversion between the internal and external representations is very easy. To
convert from the internal representation to the external, printf or fprintf is used in
almost all cases.
Explain Binary file in c
Binary fileis a collection of bytes. In C, a byte and a character are equivalent. Hence,
a binary file is also referred to as a character stream, but there are two essential
differences.
First, the data that is written into and read from remain unchanged, with no
separation between lines and no use of end-of-line characters. The NULL and end-
of-line charactershave no special significance and are treated like any other byte of
data.
Second, the interpretation of the file is left to the programmer. C places no construct
on the file, and it may be read from, or written to, in any manner chosen by the
programmer.
List out Different operations that can be performed on a file:
Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w+”)
Opening an existing file (fopen)
Reading from file (fscanf or fgets)
Writing to a file (fprintf or fputs)
Moving to a specific location in a file (fseek, rewind)
Closing a file (fclose)
Using Files in C
To use a file, four essential actions should to be carried out.
These are as follows:
Declare a file pointer variable.
Open a file using the fopen() function.
Process the file using suitable functions.
Close the file using the fclose() function.
Declare a file pointer variable.
This is accomplished by using a variable called a file pointer, a pointer variable that
points to a structure FILE. FILE is a structure declared in stdio.h.

SIVA SIVNI DEGREE COLLEGE 201 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
In C language, we use a structure pointer of file type to declare a file.
This pointer is used in all subsequent operations on the file.
The syntax for declaring file pointers is as follows:
FILE *file_pointer_name,…;
For example,
FILE *ifp;
FILE *ofp;
declares ifp and ofp to be FILE pointers. Or, the two FILE pointers can be declared
in just one declaration statement as shown below.
FILE *ifp, *ofp;
The * must be repeated for each variable.
Open a file using the fopen() function.
The fopen() function is used to create a new file or to open an existing file.
Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened
(or created) file.
filename is the name of the file to be opened and mode specifies the purpose of
opening the file.
We can use one of the following modes in the fopen() function.
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
The fopen function works in the following way.
Firstly, It searches the file to be opened.
Then, it loads the file from the disk and place it into the buffer. The buffer is used to
provide efficiency for the read operations.
It sets up a character pointer which points to the first character of the file.
Consider the following example which opens a file in write mode.
Open, Write and Close a text file
#include <stdio.h>
#include <stdlib.h>
int main() {
char grade;
FILE *file_pointer;
fptr = fopen("C:\\myfile.txt","w"); //opening myfile.txt
if(filepointer == NULL) {
printf("Error! Could not open myfile.txt");
exit(1);
}

SIVA SIVNI DEGREE COLLEGE 202 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
printf("Enter text to input in file : ");
scanf("%c",&grade);
fprintf(filepointer,"%c",grade);
fclose(filepointer);
return 0;
}
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
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.
Open, Read and Close a text file
#include <stdio.h>
#include <stdlib.h>
int main() {
char data[30];
FILE *filepointer;
filepointer = fopen("C:\\myfile.txt","r");
if (filepointer == NULL){
printf("Error! Could not opening myfile.txt");
return 1;
}
printf("Reading the file myfile.txt");
while(fgets(data, 50, filepointer) != NULL)
printf("%s", data);
printf("Closing myfile.txt");
fclose(filepointer);
return 0;
}
Write about working with text files
C provides four functions that can be used to read text filesfrom the disk.
These are
fscanf()
fgets()
fgetc()
fread()
C provides four functions that can be used to write textfiles into the disk.
These are
fprintf()
fputs()
fputc()
fwrite()
Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])

SIVA SIVNI DEGREE COLLEGE 203 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Reading File : fscanf() function
The fscanf() function is used to read set of characters from file. It reads a word from
the file and returns EOF at the end of file.
Syntax:int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Output:
Hello file by fprintf...
getc( ) and fgetc( ) functions
The functions getc() and fgetc() are identical and can be used interchangeably. They
input a single character from the specified stream. The following is the prototype of
getc() in
stdio.h.
int getc(FILE *fp);
The argument fp is the pointer returned by fopen() when the file is opened. The
function returns the character that was input or it returns EOF on error.
Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a
character to a stream.
Syntax:int fputc(int c, FILE *stream)
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
Output file : file1.txt
a

SIVA SIVNI DEGREE COLLEGE 204 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from
the stream. It returns EOF at the end of file.
Syntax:int fgetc(FILE *stream)
Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("myfile.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
getch();
}
Now open file from current directory. For windows operating system, go to TC\bin
directory, you will see emp.txt file. It will have following information.
myfile.txt
this is simple text message
The fputs() and fgets() in C programming are used to write and read string from
stream.
Writing File : fputs() function
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax:
int fputs(const char *s, FILE *stream)
Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);

fclose(fp);
getch();
}
myfile2.txt
hello c programming
Reading File : fgets() function
The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax:char* fgets(char *s, int n, FILE *stream)

SIVA SIVNI DEGREE COLLEGE 205 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Example:
void main(){
FILE *fp;
char text[300];
clrscr();
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));

fclose(fp);
getch();
}
Output:hello c programming

Define End of File (EOF) and expain with example


When reading from a file, how can the program detect that it has reached the end of
the file? There are two ways to detect end-of-file.
When reading from a text-mode file character by character, one can look for the end-
of-file character. The symbolic constant EOF is defined in stdio.h as -1, a value never
used by a ‘real’ character. When a character input function reads EOF from a text-
mode stream, it ensures that it has reached the end of the file.
For example, one could write the following.
while((c = fgetc(fp)) != EOF)

Explain the method of Working with Binary Files


The operations performed on binary files are similar to text files since both types of
files can essentially be considered as streams of bytes.
Binary files contain collection of bytes (0's and 1's).
These files contain binary numbers which is not easily editable and readable
content.
These files are highly secure and takes less space as compare to text file.
These files have extension .bin.

SIVA SIVNI DEGREE COLLEGE 206 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
To illustrate a binary file, consider the following program containing a function,
filecopy(), that is passed the names of the source and destination files and then
performs the copy operation just as the outlined steps. If there is an error in opening
either file, the function does not attempt the copy operation and returns -1 to the
calling program. When the copy operation is complete, the program closes both files
and returns 0.
The steps for copying a binary file into another are as follows.
1. Open the source file for reading in binary mode.
2. Open the destination file for writing in binary mode.
3. Read a character from the source file. Remember, when a file is first opened, the
pointer is automatically at the start of the file, so there is no need to position the
file pointer.
4. If the function feof() indicates that the end of the source file has been reached, then
close both files and return to the calling program.
5. If end-of-file has not been reached, write the character to the destination file, and
then go to step (3)
Writing to a binary file
In C programming, the fwrite() function is used to write into a binary file.
Syntax
fwrite(address, size, numbers, pointer);
Here,
address -> Address of data
size -> Size of data
numbers -> Number of such type of data
pointer -> Pointer to the file where you want to write
Reading from a binary file
In C programming, the fread() function is used to read a binary file.
fread(address, size, numbers, pointer);
Here,
address -> Address of data
size -> Size of data
numbers -> Number of such type of data
pointer -> Pointer to the file where you want to write

list out Different Mode of Operations to perform on a Binary File


Different Mode of Operation for a Binary File
Mode Meaning
rb Open a file for reading in binary mode.
wb Open a file for writing in binary mode.
ab Open a file for appending in binary mode.
Data is added to the end of the file.
rb+ or wb+ Open a file for both reading and writing in binary mode.
ab+ Open a file for both reading &appending in binary mode.
Open, Write and Close a Binary file
#include <stdio.h>
#include <stdlib.h>
struct studentData
{
char name[50];
int age;
} student;
SIVA SIVNI DEGREE COLLEGE 207 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
int main() {
int n, i, num;
FILE *filepointer;
filepointer = fopen("C:\\student.txt", "wb");
if(filepointer == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Enter the number of records you want to enter: ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
printf("\nEnter details of employee %d \n", i + 1);
fflush(stdin);
printf("Name: ");
gets(student.name);
printf("Age: ");
scanf("%d", &student.age);
num = fwrite(&student, sizeof(student), 1, filepointer);
printf("Number of items written to the file: %d\n", num);
}
fclose(filepointer);
return 0;
}
Output
Enter the number of records you want to enter: 2
Enter details of employee 1
Name: Allen
Age: 16
Number of items written to the file: 1
Enter details of employee 2
Name: Otish
Age: 34
Number of items written to the file: 1
Note : The fflush() is used to flush the output buffer of the stream. It return 0 if it is
successful.
Open, Read and Close a Binary file
#include <stdio.h>
#include <stdlib.h>
struct studentData {
char name[50];
int age;
} student;
int main() {
int n, i, num;
FILE *filepointer;
filepointer = fopen("C:\\student.txt", "wb");
if(filepointer == NULL) {
printf("Error opening file\n");
exit(1);
}
SIVA SIVNI DEGREE COLLEGE 208 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
while(fread(&student, sizeof(student), 1, filepointer) == 1 ) {
printf("Name: %s \n", student.name);
printf("Age: %d \n", student.age);
}
fclose(filepointer);
return 0;
}
Output
Name: Rob
Age: 19
Name: Jake
Age: 14
Explain about Direct File Input and Output
Direct I/O is used only with binary-mode files.
With direct output, blocks of data are written from memory to disk. Direct input
reverses the process. A block of data is read from a disk file into memory.
For example, a single direct-output function call can write an entire array of type
double to disk, and a single direct-input function call can read the entire array from
disk back into memory.
Direct File Input and Output:
Direct input and output is only with binary-mode files. With direct output, blocks of
data are written from the memory to disk. Direct input reverses the process. A block
of data is read from a disk file into memory.
fread() and fwrite() functions are used to read and write the binary files on direct I/O.
example:
const char *mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt", "wb");
if (bfp)
{
fwrite(mytext, sizeof(char), strlen(mytext), bfp) ;
fclose(bfp) ;
}
The C file system includes two important functions for direct I/O: fread() and
fwrite().
These functions can read and write any type of data, using any kind of
representation.
Their prototypes are
size_t fread(void *buffer, size_t size, size_t num,FILE *fp);
size_t fwrite(void *buffer, size_t size, size_t num, FILE *fp);
The fread() function reads from the file associated with fp, num number of objects,
each object size in bytes, into buffer pointed to by buffer. It returns the number of
objects actually read. If this value is 0, no objects have been read, and either end-of-
file has been encountered or an error has occurred.
The fwrite() function is the opposite of fread(). It writes to file associated with fp,
num number of objects, each object size in bytes, from the buffer pointed to by
buffer. It returns the number of objects written. This value will be less than num
only if an output error has occurred.
To check for errors, fwrite() is usually programmed as follows:
if((fwrite(buffer, size, num, fp)) != num)
fprintf(stderr, “Error writing to file.”);
The following program describes the use of fread() and fwrite() functions.
SIVA SIVNI DEGREE COLLEGE 209 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
The program initializes an array. Then, the fwrite() function is used to save the array
to disk. After that, the fread() function is used to read the data into a different array.
Finally, it displays both the arrays on screen to show that they now hold the same
data.
#include <stdlib.h>
#include <stdio.h>
#define SIZE 10
int main()
{
int i, a[SIZE], b[SIZE];
FILE *fp;
for(i = 0; i < SIZE; i++)
a[i] = 2 * i;
if((fp = fopen(“dfile.txt”, “wb”)) == NULL)
{
fprintf(stderr, “Error opening file.”);
exit(1);
}
if(fwrite(a, sizeof(int), SIZE, fp) != SIZE)
{
fprintf(stderr, “Error writing to file.”);
exit(1);
}
fclose(fp);
if((fp = fopen(“dfile.txt”, “rb”)) == NULL)
{
fprintf(stderr, “Error in opening file.”);
exit(1);
}
if(fread(b, sizeof(int), SIZE, fp) != SIZE)
{
fprintf(stderr, “Error in reading file.”);
exit(1);
}
fclose(fp);
for(i = 0; i < SIZE; i++)
printf(“%d\t%d\n”, a[i], b[i]);
return 0;
}

Output
00
22
44
66
88
10 10
12 12
14 14
16 16
18 18
SIVA SIVNI DEGREE COLLEGE 210 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM

/* program to copy the binary file from another file */


void main()
{
FILE *fp,*fp1;
char *s,*s1;
int ch;
clrscr();
printf("\n enter the source file : ");
gets(s);
printf("\n enter the destination file : ");
gets(s1);
fp=fopen(s,"rb");
fp1=fopen(s1,"wb");
ch=fgetc(fp);
while(!feof(fp))
{
fputc(ch,fp1);
ch=fgetc(fp);
}
fclose(fp);
fclose(fp1);
getch();
}
Breifly discuss about Files of Records
Most C program files may be binary files, which can logically be divided into fixed-
length records. Each record will consist of data that conforms to a previously defined
structure. In C, this structure can be formed using a struct data type.
The records are written into disk sequentially. This happens because as each record
is written to disk, the file position indicator is moved to the byte immediately after
the last byte in the record just written. Binary files can be written sequentially to the
disk or in a random access manner.
Working with Files of Records
Using fscanf() and fprintf() The following structure records the code, name, and price
of an item. Using this structure, a file of records can be processed. Here, 0 is used as
end-of-file marker (logically) to indicate there are no records in the file.
Example:
/* Program to append , modify and display the records using files of records */
struct item
{
int itemcode;
char name[30];
double price;
};
void append();
void modify();
void dispall();
void dele();

SIVA SIVNI DEGREE COLLEGE 211 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
int main()
{
int ch;
struct item it;
FILE *fp;
fp=fopen(“item.dat”,”w”);
if(fp==NULL)
printf(“\n Error in opening the file … ”);
printf(“\n enter the ITEM code :”);
scanf(“%d”,&it.itemcode);
printf(“\n Enter the ITEM name : ”);
scanf(“%s”,&it.name);
printf(“\n Enter the price : ”);
scanf(“%lf”,&it.price);
fprintf(fp,”%d \t %s \t %lf \n”,it.itemcode,it.name,it.price);
fprintf(fp,”%d”,0);
fclose(fp);
while(1)
{
printf(“\n 1. Append records …”);
printf(“\n 2. Display all the records …”);
printf(“\n 3. Edit the records …”);
printf(“\n 4. Delete the records …”);
printf(“\n 5. Exit …”);
printf(“\n Enter your choice …”);
scanf(“%d”,&ch);
}
switch(ch)
{
case 1: append(); break;
case 2: dispall(); break;
case 3: modify(); break;
case 4: dele(); break;
case 5: exit(0); break;
}}
void append()
{
FILE *fp;
struct item it;
fp=fopen(“item.dat”,”r”);
if(fp==NULL)
printf(“\n Error in opening a file …”);
printf(“\n enter the ITEM code :”);
scanf(“%d”,&it.itemcode);
printf(“\n Enter the ITEM name : ”);
scanf(“%s”,&it.name);
printf(“\n Enter the price : ”);
scanf(“%lf”,&it.price);
fprintf(fp,”%d \t %s \t %lf \n”,it.itemcode,it.name,it.price);
fprintf(fp,”%d”,0);
fclose(fp); }
SIVA SIVNI DEGREE COLLEGE 212 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
void dispall()
{
FILE *fp;
struct item it;
fp=fopen(“item.dat”,”r”);
if(fp==NULL)
printf(“\n Error in opening a file …..”);
while(1)
{
fscanf(fp,”%d”,&it.itemcode);
if(it.itemcode==0)
break;
fscanf(fp,”%s”,it.name);
fscanf(fp,”%lf”,&it.price);
fprintf(fp,”%d \t %s \t %lf \n”,it.itemcode,it.name,it.price);
}
fclose(fp);
}
void modify()
{
FILE *fp,*fptr;
struct item it;
int icd,found=0;
fp=fopen(“item.dat”,”r”);
if(fp==NULL)
printf(“\n Error in opening a file ”);
fptr=fopen(“temp.dat”,”w”);
if(fptr==NULL)
printf(“\n Error in opening a file ”);
printf(“\n Enter the Item code to edit”);
scanf(“%d”,&icd);
while(1)
{
fscanf(fp,”%d”,&it.itemcode);
if(it.itemcode==0)
break;
if(it.itemcode==icd)
{
found=1;
fscanf(fp,”%s”,it.name);
fscanf(fp,”%lf”,&it.price);
printf(“\n Existing record is ………. \n”);
fprintf(fp,”%d \t %s \t %lf \n”,it.itemcode,it.name,it.price);
printf(“\n Enter the new ITEM name : ”);
scanf(“%s”,&it.name);
printf(“\n Enter the new item price : ”);
scanf(“%lf”,&it.price);
fprintf(fp,”%d \t %s \t %lf \n”,it.itemcode,it.name,it.price);
}

SIVA SIVNI DEGREE COLLEGE 213 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
else
{
fscanf(fp,”%s”,it.name);
fscanf(fp,”%lf”,&it.price);
fprintf(fp,”%d \t %s \t %lf \n”,it.itemcode,it.name,it.price);
}
}
fclose(fptr);
fclose(fp);
}
void dele()
{
FILE *fp,*fptr;
struct item it;
int icd,found=0;
fp=fopen(“item.dat”,”r”);
if(fp==NULL)
printf(“\n Error in opening a file ”);
fptr=fopen(“temp.dat”,”w”);
if(fptr==NULL)
printf(“\n Error in opening a file ”);
printf(“\n Enter the Item code to delete”);
scanf(“%d”,&icd);
while(1)
{
fscanf(fp,”%d”,&it.itemcode);
if(it.itemcode==0)
break;
if(it.itemcode==icd)
{
found=1;
fscanf(fp,”%s”,it.name);
fscanf(fp,”%lf”,&it.price);
}
else
{
fscanf(fp,”%s”,it.name);
fscanf(fp,”%lf”,&it.price);
fprintf(fp,”%d \t %s \t %lf \n”,it.itemcode,it.name,it.price);
}
}
fclose(fptr);
fclose(fp);
}

SIVA SIVNI DEGREE COLLEGE 214 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Example programs on text files:
/* Read a string into a text file using fputs() function */
void main()
{
FILE *fp;
char text[80];
int i;
clrscr();
fp=fopen("Sample.txt","w");
printf("\n Enter the text : ");
gets(text);
fputs(text,fp); //write a string into a file
if(fp!=NULL)
printf("\n The string copied into a text file ");
fclose(fp);
getch();
}
/* Program to copy from one file to another file */
void main()
{
FILE *fp,*fp1;
int ch;
clrscr();
fp=fopen("ex_file4.c","r");
fp1=fopen("ex_file2.c","w");
if(fp==NULL)
printf(“File is not available”);
ch=getc(fp);
while(ch!=EOF)
{
putc(ch,fp1);
ch=getc(fp);
}
fclose(fp);
fclose(fp1);
getch();
}
/* Program to display the content of the file */
void main()
{
FILE *fp;
int ch;
clrscr();
fp=fopen("ex_file4.c","r");
if(fp==NULL)
printf(“File is not available”);
ch=getc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp); }
SIVA SIVNI DEGREE COLLEGE 215 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
fclose(fp);
getch();
}
/* read and write the content of the file using fprintf() and fscanf() functions */
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
clrscr();
/* open for writing */
fptr = fopen("abc.txt", "w");
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %f\n", salary);
getch();
fclose(fptr);
}
Explain about Random Access to Files of Records
For random access to files of records, the following functions
are used.
fseek()
ftell()
rewind()
For random access to files of record, the following functions are used.
1. fseek() -- by using fseek(), one can set the position indicator anywhere in the file.
It’s prototype is,
int fseek(FILE *fp,long offset,int origin);
It has the origins as, SEEK_SET, SEEK_CUR,SEEK_END
2. ftell() --- To determine the value of a file’s position indicator, use ftell(). The
prototype is,
long ftell(FILE *fp);
3. rewind() ------ To set the position indicator to the beginning of the file, use the
function rewind().
Its prototype is,
void rewind(FILE *fp);

SIVA SIVNI DEGREE COLLEGE 216 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
Example:
program to copy the content from one file to another file using fseek() function.
void main()
{
/*
File_1.txt is the file with content and,
File_2.txt is the file in which content of File_1
will be copied.
*/
FILE *fp1, *fp2;
char ch;
int pos;
clrscr();
if ((fp1 = fopen("File_1.txt","r")) == NULL)
{
printf("\nFile cannot be opened");
return;
}
else
{
printf("\nFile opened for copy...\n ");
}
fp2 = fopen("File_2.txt", "w");
fseek(fp1, 0L, SEEK_END); // file pointer at end of file
pos = ftell(fp1);
fseek(fp1, 0L, SEEK_SET); // file pointer set at start
while (pos--)
{
ch = fgetc(fp1); // copying file character by character
fputc(ch, fp2);
}
getch();
fcloseall();
}
Write about Other File Management functions
The copy and delete operations are also associated with file management. Though
one could write programs for them, the C standard library contains functions for
deleting and renaming files.
Deleting a file
The library function remove() is used to delete a file. Its prototype is,
int remove(const char *filename);
Renameing a file :
The rename() function changes the name of an existing disk file. Its prototype is,
int rename(const char *oldname, const char *newname);
Example:
int main()
{
char file[80];
/* prompt for filename to delete */
printf(“File to delete :”);
gets(file);
SIVA SIVNI DEGREE COLLEGE 217 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
/* delete the file */
if(remove(file)==0)
printf(“removed %s”,file);
else
printf(“file cannot be removed”);
}
Explain Low – Level I/O in c
This form of I/O is unbuffered. That is, each read or write request results in
accessing the
disk directly to fetch/put a specific number of bytes. There are now formatting
facilities. Instead of file pointers, we use low-level file handles or file descriptors,
which give a unique integer number to identify each file.
To open a file the following function is used.
int open(char *filename, int flag, int perms);
To create a file the following function is used.
creat(char *filename, int perms);
To close the file the following function is used.
int close(int handle);
Creating the header files in C
Creating the header files using the following steps,
Step 1: Create the function, using function header and function body.
Example:
int add(int a,int b)
{
c=a+b;
return c;
}
Step 2: Save the above function using [ .h ] extension. and compile the code.
Example:
above function can be save as myhead.h.
Step 3: Write the main program, include our own header file in the program. Now
main function automatically includes the function available in the header file.
Example:
#include<stdio.h>
#include ”myhead.h”
void main()
{
int num1=10,num2=20,num3;
num3=add(num1,num2);
printf(“\n Sum of two numbers is : %d”,num3);
}
Note : When running the program, header file and the program must be present in
the same folder.

SIVA SIVNI DEGREE COLLEGE 218 | P a g e


PROGRAMMING IN C Bsc I YR/I-SEM
IMPORTANT QUESTIONS
1. Define a structure and declare and initialize a structure
2. How to declaring structure variables?
3. How to access structure members?
4. Write about arrays in structures
5. Discuss about array of structures
6. Define how structures can be nested
7. How to copy structures into another structure?
8. Discuss about passing structures as arguments in functions
9. Difference between array and structure
10. Difference between structure and union
11. Discuss about structures and pointers
12. Define union and explain creating declaring and initializing a union
13. How Pointer used in a union
14. How to Access members using Pointer?
15. Define Enumerator
16. Write a program to illustrate the assignment of default values to the
members of data type enum.
17. Explain files in c in detailed
18. Explain text file in c
19. Explain the method of Working with Binary Files
20. List out Different operations that can be performed on a file:
21. Explain Open, Write and Close a text file
22. List out read text files from the disk with example
23. List out write text files into the disk with example
24. Define End of File (EOF) and explain with example
25. Explain about Direct File Input and Output
26. Briefly discuss about Files of Records
27. Explain about Random Access to Files of Records
28. Write about Other File Management functions
29. Explain Low – Level I/O in c
30. How to create the header files in C

SIVA SIVNI DEGREE COLLEGE 219 | P a g e

You might also like