Professional Documents
Culture Documents
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
1
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
2
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
1. Takes Input
The process of entering data and instructions into the computer system.
2. Stores Data
Saving data and instructions so that they are available for processing as and when
required.
3. Processing the Data
Performing arithmetic, and logical operations on data in order to convert them into
useful information.
4. Output the Information
The process of producing useful information or results for the user, such as a printed
report or visual display.
5. Control the workflow
Directs the manner and sequence in which all of the above operations are performed.
3
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
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 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.
5
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
6
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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,
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
7
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
• 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.
• 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
8
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
9
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Computers in general can be classified into major categories based on. Computers can be
classified in variety of ways on the basis of various parameters such as usage, cost, size,
processing power, and so on.
• According to the purpose of the computer.
• According to the operation size of computer.
• Various Types of Computer Systems Based On Usage
VARIOUS DIGITAL COMPUTER AS PER THE PURPOSE
General Purpose digital computers: These computers are theoretically used for any type
of applications. These computers can be 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.
10
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 Satellite launching weather forecasting etc.
VARIOUS TYPES OF COMPUTER SYSTEMS BASED ON USAGE
1. 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.
11
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
3. 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.
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
More than 50 terminals and large capacitystorage devices than microcomputers.
Used for general purpose.
Used in medium sized organizations andcorporation for their database administration.
3. Mainframe Computer
Are the largest types of computers
Are used in large organizations like insurance companies, banks where people need
frequent access to the same data, which is usually organized 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.
13
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
4. Super Computer
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
DEFINE GENERATION: 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. These tubes, like
electric bulbs, produced a lot of heat and 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 and Generated a lot of heat
Slow input and output devices
Huge size
14
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
More reliable in comparison to previous two generations
Smaller size
Generated less heat
Faster
15
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 −
DEC 10
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
16
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Game Playing
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
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
17
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
18
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
o 101 – Key enhanced keyboard, 104 – key windows keyboard.
o 82 – Key Apple standard keyboard and 108- key Apple extended keyboard.
o It contains alphabets (A to Z or a to z), digits (0 to 9), special characters (!@,#,$,
%,^,&,*,<,>,? etc) and some control keys.
There are five key groups:
o 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.
o 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
o 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.
o Function Keys
Middle of top row
Labeled F1 to F12
o 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.
19
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
21
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
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)
22
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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)
23
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
24
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
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.
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.
Dot matrix printers normally come in two sizes—80 column printer and 132 column
printers.
Dot matrix printers 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.
27
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
drum rotates at a very high speed and characters are printed by activating the appropriate
hammers.
o 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.
o 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.
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.
28
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 four cartridges 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 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
Printing Speed
Running Cost
Resolution
Duplex Printing
Printer Size
Needed Functions
Media Handling
Monochrome vs. Color
EXPLAIN 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—
29
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
31
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Speech to text is software that works by listening to audio and delivering an editable,
verbatim transcript on agiven 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
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.
32
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
WRITE ABOUT 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:
4) 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.
5) Byte: It is the fundamental unit to measure data.
6) It contains 8 bits or is equal to 8 bits. Thus a bytecan represent 2*8 or 256 values.
7) Kilobyte: A kilobyte contains 1024 bytes.
8) Megabyte: A megabyte contains 1024 kilobytes.
9) 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.
33
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
34
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
35
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 –
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)
36
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
37
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
38
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
3. 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
Optical Disks
Magnetic Tapes.
Solid State Devices
Understanding the characteristics of each of them would help you choose the most
appropriate storage device to hold your data.
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
39
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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)
40
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
41
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
42
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Blu-ray disks are currently the most commonly used forms of optical disks.
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
43
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.)
44
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
48
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
49
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
50
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
DISCUSS 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 steps
which the CPU carries out for each machine language instruction are fetch, decode, execute,
and store.
51
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
WRITE ABOUT 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
1. The way its stores the data and instructions
2. How it manipulate input and output
3. The operators it uses to transfer and combine the data
DISCUSS ABOUT 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.
52
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
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
53
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
54
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
55
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
56
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
DEFINE 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.
DEFINE 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. The features of a programming language influence
the linking requirements of a program.
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.
WHAT ARE PHASES OF PROGRAM DEVELOPMENT
Program development life cycle contains 6 phases, which are as follows −
57
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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:
58
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
WRITE A SHORT NOTE ON 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.
1. Feasibility study
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
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.
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
60
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
WHAT ARE THE 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
Pseudo-code
Flowchart
61
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
62
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
64
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
65
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
66
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
67
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
68
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 description
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.
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:
1. Step 1: Define the complete scope of the problem to determine the basic requirement
for its solution. Three factors must 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 type of processing is required?
Output What information should the program produce? In what form should it be
presented?
2. Step 2: Based on the definition of the problem, divide the problem into two or more
separate parts.
3. Step 3: Carefully define the scope of each of these separate tasks and subdivide them
further, if necessary, into two or more smaller tasks.
4. Step 4: R epeat step 3. Every step at the lowest level describes a 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.
69
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 a
well-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.
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.'
70
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
1972
'C' Programming Language was
Dennis.M developed by Dennis Ritchie at
C Ritchie at AT & T Bell Laboratories in
AT&T' 1972. This is general purpose,
Bell Laboratory. compiled, structured
programming language.
Dennis Ritchie studied the
BCPL, then improved and
named it as 'C' which is the
second letter of
BCPL
71
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
INTRODUCTION TO 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.
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 areindependently 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 as
single 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, ifthe
72
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
74
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
· 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.
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 = "javatpoint";
o Errors in expressions
int a, b, c;
a+b = c;
o Array index out of bound
int a[10];
a[10] = 34;
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 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++
2. Create turboc directory inside c drive and extract the tc3.zip inside c:\turboc
3. Double click on install.exe file
4. 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;
}
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 which
include name of a program, author name, creation date and other information.
DEFINE COMMENTS: Comment line is used for increasing the readability of the
program. It isuseful 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.
77
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
78
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Definition means declaration of a data object and also allocating space to hold the data
object.
Digits 0-9
Special Character !@#$%^&*
White space Tab or new lines or
space
EXPAIN ABOUT TOKENS IN C
Define Identifier:
Identifier is the name of a variable that is made up from
combination of alphabets, digits and underscore.
Identities are names given to various program elements like variables, arrays and functions
and lables are named.
Rules:
The name should begin with a letter and other characters can be letters and digits
and also can contain underscore character (_)
Identifier is significant up to 32 characters.
It can’t duplicate a reserved word.
Both upper and lower case are allowed.
Example: area, average, x12, name_of_place etc………
Identifiers are also case sensitive in C. For example name and Name are two
different identifiers in C.
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.
80
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Several keywords were added in C89: const, enum, signed,void, and volatile. The new
keywords in C99 are inline, restrict, _Bool, _Complex, and _Imaginary.
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
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
82
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
84
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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”;
85
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
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.)
87
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
88
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
89
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Increment and decrement operators
• Conditional operators
• Misc Operators
Arithmetic operator:
These are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.
There are three types of arithmetic operators in C: binary, unary, and ternary.
Binary operators
C provides five basic arithmetic binary operators.
90
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
Bit wise operators in C language are; & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^
(XOR), << (left shift) and >> (right shift).
91
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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:
Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.
There are following assignment operators supported by C language:
92
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 decrement the value of a variable by 1.
There are ‘pre’ and ‘post’
variants for both operators that do slightly different things as explained 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.
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.
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.
Misc Operators: There are few other operators supported by c language.
93
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 expression 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
94
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
95
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
96
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
97
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 os & 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. Define Identifiers?how it is different from varable
24. Define Data type,explain primary data types in c
25. Define Variables 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. Define Type conversions explain types of it
98
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
UNIT-II
INPUT OUTPUT FUNCTIONS OF C LANGUAGE (STATEMENTS):
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>
99
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
main()
{
clrscr() ;
printf(“Hello” );
printf(“Bhanodaya “) ;
printf(“Welcome “) ;
}
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();
100
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
#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
102
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Display the keyed-in character and the next character from the ASCII table.
Solution
#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.
Solution
#include<stdio.h>
int main(void)
{
putchar(getchar());
return 0;
}
Input y
Output y
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 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.]
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
inclusion
the main program at the specified place.
103
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
105
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
Note:In case the statement block contains only one statement, putting curly brackets
becomes 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;
106
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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;
}
107
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
For example, the following code tests whether a number entered by the user is negative,
positive, or equal to zero.
int main()
{
108
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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; }
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.
109
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
Nested if
When any if statement is written under another if statement,this cluster is called a nested
if.
#include <stdio.h>
int main()
{
int a, b, c;
printf(“\nEnter the three numbers”);
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}
Switch vs nested if
The switch differs from the else-if in that switch can test only for equality, whereas the if
conditional expression can be a test of an expression involving any type of relational
operators and/or logical operators.
A switch statement is usually more efficient than nested ifs.
111
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
The switch statement can always be replaced with a series of else-if statements.
One may only use switch and case statements if an expression is required to check against
a finite amount of constant, integral, or character values.
If there are too many values and if any of the values depends on variables, or if the values
are not integers or characters, one must use a series of else-if statements.
Even when one can use switch efficiently, it is just a matter of personal preference whether
one decides to use a switch statement or else-if statements.
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
112
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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;
}
113
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
114
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
#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;
}
115
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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).
116
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
#include <stdio.h>
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; }
#include<stdio.h>
#include<conio.h>
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++)
117
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
{
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 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, the break statement is used to terminate the execution of the
nearest enclosing loop in which it appears. We have already seen its use in the switch
statement. The break statement is widely used with for, while, and do–while loops.
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;
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)
118
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
{
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
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.
119
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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;
}
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.
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;
}
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.
120
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
Following is the C program for use of exit() function −
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; }
121
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 ()
{
// declaration of the variables
int i, num;
printf ( " Enter the last number: ");
scanf ( " %d", &num);
for ( i = 1; i<num; i++)
{
// use if statement to check the condition
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
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.
122
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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];
Type of Arrays
• One / Single Dimensional Array
• Two Dimensional Array
• Multi-Dimensional Array
123
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
124
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
125
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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;
}
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.
#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, arr[20], small, pos;
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements : ");
for(i=0;i<n;i++)
126
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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;
}
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];
127
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
128
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
{
printf("%d\t", arr[i][j]); }
printf("\n");
}
return 0;
}
Output
12 34
56 32
}
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();
}
1. Write a program to input two m \ n matrices and then calculate the sum of their
corresponding elements and store it in a third m \ n matrix.
2. Write a program to multiply two m \ n matrices. 3. Write a program to Transpose of a
matrix
Discuss about Multi-Dimensional Array:
More than 2-dimensional arrays are treated as multidimensional 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.
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} } }
130
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
How to Pass the Entire Array
We already discussed that in C the array name refers to the first byte of the array in the
memory. The address of the remaining elements in the array can be calculated using the
array name and the index value of the element. Therefore, when we need to pass an entire
array to a function.
Write a program to read an array of n numbers and then find the smallest number.
132
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
#include <stdio.h>
int main ()
{
printf ("Catch me if you can.");
}
“ctype.h” header file support all the below functions in C language. Click on each
function name below for detail description and example programs.
133
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
134
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
ceil(9.2) is 10.0
ceil(x) rounds x to smallest integer not ceil(-9.2) is -9.0
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-point 1.992
number
sin(x) sine of x (x in radian) sin(0.0) is 0.0
#include <stdio.h>
#include <conio.h>
#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));
136
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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;
}
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
137
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
138
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
#include<stdio.h>
#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; }
139
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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);
char name[50];
scanf("%s",name);
printf("%s",name);
#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
140
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
FunctionName Description
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”))
141
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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);
strcat( ): this string function is used to concatenate(add) two strings. (Second string
can beadded to first string ).
Syntax : strcat(string1,string2);
2) 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.
3) 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.
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.
4) 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.
142
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
143
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
7) strupr() function :
strupr() function converts a given string into uppercase.
Syntax : char *strupr(char *string);
strupr() function is non standard function which may not available in standard library
in C. 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<st
dio.h>
#include<st
ring.h> int
main()
{
char str[ ] = “Modify This String To
Upper”;printf(“%s\n”, strupr(str));
return 0;
}
Output : MODIFY THIS STRING TO UPPER
8. strrev() function :
strrev() function reverses a given string in C language.
Syntax : char *strrev(char *string);
strrev() function is non standard function which may not available in standard
library in C.
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”.
#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
Pointers and Arrays
Array notation is a form of pointer notation. The name of the array is the starting
address of the array in memory. It is also known as the base address. In other words,
base address is the address of the first element in the array or the address of arr[0].
Now let us use a pointer variable as given in the statement below.
Int arr[10]; int *ptr;
ptr = &arr[0]; or ptr=&arr;
Here, ptr is made to point to the first element of the array.
Write a program to display an array of given numbers.
#include <stdio.h>
int main()
{
144
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
int arr[]={1,2,3,4,5,6,7,8,9};
int *ptr1, *ptr2; ptr1 = arr;
ptr2 = &arr[8];
while(ptr1<=ptr2)
{
printf("%d", *ptr1); ptr1++;
}
return 0;
}
Output
123456789
Arrays of Pointers
An array of pointers can be declared as int *ptr[10];
The above statement declares an array of 10 pointers where each of the pointer
points to an integer variable.
int *ptr[10];
int p = 1, q = 2, r = 3, s = 4, t = 5;
ptr[0] = &p;
ptr[1] = &q;
ptr[2] = &r;
ptr[3] = &s;
ptr[4] = &t;
Example:
#include <stdio.h>
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr[3];
for ( i = 0; i < 3; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < 3; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0; }
145
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
146
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
Types of functions:
1. Pre-Defined (Built in) Functions 2. User Defined 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.
147
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
After the called function is executed, the control is returned to the calling program.
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.
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();
148
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
149
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
#include <stdio.h>
#include<conio.h>
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;
}
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 “) }
150
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 .
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); }
151
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 .
152
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
EX: #include<stdio.h>#include<conio.h>
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.
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.
153
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
#include<stdio.h>
#include<conio.h>
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);
}
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 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.
154
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
#include<stdio.h>
#include<conio.h>
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
155
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
Actual and formal arguments will be Actual and formal arguments willbe
created in different memory location created in same memory location
156
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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
}
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 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.
157
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
158
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
160
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
161
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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.
Define 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
162
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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 ;
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.
/* 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(); }
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
HOW POINTER IS ASSOCIATED WITH FUNCTIONS
Passing array to function using call by value method
As we already know in this type of function call, the actual parameter is copied to
the formal parameters.
call by value :
in call by value simple variables are sent to the functions in the form of arguments.
In this case only values of the arguments are copied to the corresponding function
parameters. When we make some changes to variables in the function, it does not
affect the variables of the calling function.
Example:
void swap(int,int);
main( )
{
int a=30,b=40;
swap(a,b);
printf(‘’\n after swap a=%d, b=%d’’,a,b);
getch( );
}
166
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
167
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Output
5 10
10 5
2. #include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return 0;
}
Output: 1 2 3 4 5 6 7 8 9 0
How to pass an entire array to a function as an argument?
In the above example, we have passed the address of each array element one by one using
a for loop in C. However you can also pass an entire array to a function like this:
Note: The array name itself is the address of first element of that array. For example if array
name is arr then you can say that arr is equivalent to the &arr[0].
#include <stdio.h>
void myfuncn( int *var1, int var2)
{
/* the pointer var1 is pointing to the first element of the array and the var2 is the size of
the array. In the loop we are incrementing pointer so that it points to the next element of
the array on each increment.*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);/*increment pointer for next element
fetch*/
168
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Output:
Value of var_arr[0] is: 11
Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77
WRITE 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 example1
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 −
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 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
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.
169
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Examples:
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
You can also use an array of pointers to character to store a list of strings as follows
#include <stdio.h>
const int MAX = 4;
int main () {
char *names[] = { "saiprasad", "gopinath", "sriram", "krishna" };
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of names[0] = saiprasad
Value of names[1] = gopinath
Value of names[2] = sairam
Value of names[3] = krishna
WRITE ABOUT POINTER TO A STRUCTURE IN C
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.
struct student
{
char name[10];
char group[10];
int age;} s1;// declaring a pointer to a structure of type struct student
171
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Arrays Pointers
Arrays allocate space It is explicitly assigned to point
automatically. to an allocated space.
It cannot be resized. It can be resized.
It cannot be reassigned. It can be reassigned.
sizeof(arrayname) gives the sizeof(p) returns the number of
number of bytes occupied by the bytes used to store the pointer
array. variable p.
Discuss about Pointers and Strings
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.
#include <stdio.h>
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.
#include <stdio.h>
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
Example:1
#include <stdio.h>
int main(void)
{
int a[] = {10, 12, 6, 7, 2};
int i;
int sum = 0;
for(i=0; i<5; i++)
{
sum += *(a + i);
}
printf(“%d\n”, sum);
return 0;
}
173
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Example:
#include<stdio.h>
int main() {
// creating a pointer variable to store the value of
// our string
char *strPtr = "HelloWorld";
// temporary pointer to iterate over the string
char *temp = strPtr;
// creating a while loop till we don't find
// a null charater in the string
while (*temp != '\0')
{
// the current character is not \0
// so we will print the character
printf("%c", *temp);
// move to the temp pointer to the next memory location
temp++;
}
return 0;
}
Explain the concept of pointers to pointers
C allows the use of pointers that point to pointers, and these, in turn, point to data.
For pointers to do that, we only need to add an asterisk (*) for each level of
reference.
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.
#include <stdio.h>
int main()
{
int a=5;
int *p,**q;
174
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
p=&a;
q=&p;
printf(“\n *p=%d”,*p);
printf(“\n **q=%d”,**q);
return 0;
}
Output
*p=5
**q=5
Consider the following declarations.
int a; /*integer variable */
int *p; /*pointer to integer */
int **q; /*pointer to pointer to integer */
a = 5; /*assign value to a */
p = &a; /*address of a is stored in p */
q = &p; /*address of pa is stored in q */
int main()
{
int a;
int *p;
int **dp;
int ***tp;
p=&a;
dp=&p;
tp=&dp;
printf(“\n ENTER THE VALUE OF a”);
scanf(“%d”,&a);
printf(“\n a=%d”,a);
printf(“\n ENTER THE VALUE OF a”);
scanf(“%d”,p);
printf(“\n a=%d”,a);
printf(“\n ENTER THE VALUE OF a”);
scanf(“%d”,*dp);
printf(“\n a=%d”,a);
printf(“\n ENTER THE VALUE OF a”);
scanf(“%d”,**tp);
printf(“\n a=%d”,a);
return 0; }
Output
ENTER THE VALUE OF a 5
a=5
ENTER THE VALUE OF a 10
a=10
ENTER THE VALUE OF a 20
a=20
ENTER THE VALUE OF a 25
a=25
Example:
175
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
#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 THE CONCEPT DYNAMIC MEMORY ALLOCATION WITH EXAMPLE
The following functions are used in dynamic memory allocation and are defined in
<stdlib.h>
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. 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));
176
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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'.
#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
178
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
179
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
180
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
UNIT-IV
User-defined Data Types and Variables
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;
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.
1. At the time of structure definition (Along with structure definition)
2. 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 (;).
Structure Initialization
Assigning constants to the members of the structure is called initializing of structure.
Syntax:
182
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
struct struct_name
{
data _type member_name1;
data _type member_name2;
} struct_var={constant1,constant2};
Ex: emp={101,”sai”,25000};
Accessing Structure members
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);
Memory of Structure variable:
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.
183
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
struct student s;
int i;
clrscr();
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]);
185
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
186
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
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;
188
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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);
}
Pointer Array name points to the first Structure name does not point
element in that array so, array to the first element in that
name is a pointer. structure so, structure name is
not a pointer.
Bit filed Bit filed cannot be defined in an Bit field can be defined in a
array. structure.
189
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
190
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
(*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.
#include <stdio.h>
#include <conio.h>
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
UNION
Define union and explain creating declaring and initializing an union
191
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
1. At the time of Union definition (Along with union definition)
2. After union definition.
192
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Union variables are declared before closing the union definition. i.e., before closing
semicolon(;).
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.
/* Program to demonstrate union. */
union techno
193
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
{
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 a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a 2. When a variable is associated with a
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 sum largest memory. So, size of union is equal
of sizes of its members. The smaller to the size of largest member.
members may end with unused slack bytes.
4. The address of each member will be in 4. The address is same for all the members
ascending order This indicates that of a union. This indicates that every
memory for each member will start at member begins at the same offset value.
different offset values.
5 Altering the value of a member will not 5. Altering the value of any of the member
affect other members of the structure. will alter other member values.
194
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
#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
How Pointer 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.
How to Access members using Pointer
There are two ways of accessing members of union using pointer:
1. Using indirection (*) operator and dot (.) operator.
2. 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
195
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
member of structure write *ptr followed by a dot(.) operator, followed by the name
of the member.
For example:
3. *ptr.name – refers to the name of student
4. *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;
}
ENUMERATORS
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 an enumeration type is
enum tag_name{member1, member2,…, memberN}
variable1,...,variableX;
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.
196
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
197
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
Output : 4 day
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( );
}
198
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
1. Text file
2. Binary file
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
specify the 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 file is 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 characters have 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+”)
1. Opening an existing file (fopen)
2. Reading from file (fscanf or fgets)
3. Writing to a file (fprintf or fputs)
4. Moving to a specific location in a file (fseek, rewind)
5. 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.
199
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
200
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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);
}
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 files from the disk.
These are
fscanf()
fgets()
fgetc()
fread()
C provides four functions that can be used to write text files into the disk.
These are
fprintf()
fputs()
201
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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, ...])
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...
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
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
203
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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)
Example:
#include<stdio.h>
#include<conio.h>
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)
205
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
#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);
}
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;
206
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
} 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);
}
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);
207
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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
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();
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;
210
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
{
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);
}
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);
213
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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);
}
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);
214
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
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.
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:
217
SIVA SIVANI DEGREE COLLEGE
PROGRAMMING IN C
218
SIVA SIVANI DEGREE COLLEGE