Module 1- Introduction to C Programming (1)
Module 1- Introduction to C Programming (1)
Prepared by
Mrs. Reshma
Assistant Professors,
Department of CS&E,
Acharya Institute of Technology
2024-2025
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
2. Problem analysis: Identify, formulate, review research literature, and analyse complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences
3. Design / development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health
and safety, and the cultural, societal, and environmental considerations
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modelling to complex engineering activities with an understanding of
the limitations
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice
11. Project management and Finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change
PEO-1 Students shall, have a successful career in academia, R&D organizations, IT industry or pursue higher
studies in specialized field of Computer Science and Engineering and allied disciplines.
PEO-2 Students shall, be competent, creative and a valued professional in the chosen field.
PEO-3 Students shall, engage in life-long learning, professional development and adapt to the working
environment quickly
PEO-4 Students shall, become effective collaborators and exhibit high level of professionalism by leading
or participating in addressing technical, business, environmental and societal challenges.
PSO-1 Students shall, apply the knowledge of hardware, system software, algorithms, networking and data
bases.
PSO-2 Students shall, design, analyze and develop efficient, Secure algorithms using appropriate data
structures, databases for processing of data.
PSO-3 Students shall, be Capable of developing stand alone, embedded and web-based solutions having easy
to operate interface using Software Engineering practices and contemporary computer programming
languages.
TABLE OF CONTENTS
MODULE 1: Introduction to C
1.1 Computer:
A computer, in simple terms, can be defined as an electronic device that is designed to accept
data, perform the required mathematical and logical operations at high speed, and output the
result.
We all have seen computers in our homes, schools, and colleges. In fact, in today‘s scenario,
we find computers in most aspects of our daily lives. For some of us, it is hard to even imagine
a world without them.
Speed: Computers can perform millions of operations per second. The speed of
computers is usually given in nanoseconds and picoseconds, where 1 nanosecond = 1×
10 −9 seconds and 1 picosecond = 1 × 10 −12 seconds.
Accuracy: A computer is a very fast, reliable, and robust electronic device. It always
gives accurate results, provided the correct data and set of instructions are input to it.
Automation: Besides being very fast and accurate, computers are automatable devices
that can perform a task without any user intervention.
Diligence: Unlike humans, computers never get tired of a repetitive task. It can
continually work for hours without creating errors.
Versatile: Versatility is the quality of being flexible. Today, computers are used
in our daily life in different fields. For example, they are used as personal
computers (PCs) for home use, for business-oriented tasks, weather forecasting, space
exploration, teaching, railways, banking, medicine, and so on,
Memory: Similar to humans, computers also have memory. Just the way we cannot
store everything in our memory and need secondary media, such as a notebook, to
record certain important things, computers also have internal or primary memory
(storage space) as well as external or secondary memory.
Generation of Computers
The word generation means the state of improvement in the product development
process. Similarly, computer generation refers to the different advancements of
new computer technology.
Highlights
They were the fastest calculating device of those times
Computers were too bulky and required a complete room for storage
Highly unreliable as vacuum tubes emitted a large amount of heat and
burnt frequently
Required air-conditioned rooms for installation
Costly
Difficult to use
Required constant maintenance because vacuum tubes used filaments
that had limited life time.
Therefore, these computers were prone to frequent hardware failures
Advantages:
Fastest calculating device of their time
Disadvantages:
Dissipate a lot of heat.
Consume a lot of electricity.
Very bulky in size.
These computers were frequently down due to hardware failures.
These computers needed constant maintenance because of low mean
time between failures.
Limited commercial use because these computers were difficult to program.
Very expensive.
Highlights :
Faster, smaller, cheaper, reliable, and easier to use than the first generation computers
They consumed 1/10th the power consumed by first generation computers
Bulky in size and required a complete room for its installation
Dissipated less heat than first generation computers but still required air-
conditioned rooms.
Costly
Difficult to use
Advantages:
Consumed less electricity and thus dissipated less heat as compared to first
generation computers.
Faster, cheaper smaller and more reliable than first generation computers.
Could be programmed using assembly language and high level languages.
These computers had faster primary memory and a larger secondary memory.
Disadvantages:
Second generation computers were manufactured using transistors that had to be
assembled manually. This made commercial production of computers difficult and
ICs consist of several components such as transistors, capacitors, and resistors on a single
chip to avoid wired interconnections between components. These computers used SSI and
MSI technology. Minicomputers came into existence.
Memory- Larger magnetic core memory was used as primary memory; larger capacity
magnetic tapes and magnetic disks were used to store data and instructions.
Software Technology - Programming was done in high level programming languages such
as FORTRAN, COBOL, Pascal, and BASIC. Time sharing operating system was
used. Software was separated from the hardware. This allowed users to invest only in the
software they need.
Used for Scientific, commercial, and interactive online applications
Examples IBM 360/370, PDP-8, PADP-11, CDC6600
Advantages:
Faster than second generation computers and could perform 1 million transactions
per second.
Smaller, cheaper and more reliable than their predecessors
These computers had faster and larger primary memory and secondary storage.
They were widely used for scientific as well as business applications.
During this generation of computers, standardization of existing high-level languages
and invention of new high level languages was done.
Advantages:
Smaller, cheaper, faster and more reliable.
Consumed less electricity and therefore dissipated less heat.
They had faster and larger primary memory and secondary storage.
They could be used as general purpose computers.
GUIs enabled people to learn to work with computers very easily. So the use of
Highlights
Faster, smaller, cheaper, powerful, reliable, and easier to use than the previous
generation computers.
Speed of microprocessors and the size of memory are growing rapidly.
High-end features available on mainframe computers in the fourth generation are now
available on the microprocessors.
They consume less power than computers of prior generations.
Supercomputers
Among the four categories, the supercomputer is the fastest, most powerful, and most
expensive computer.
Supercomputers were first developed in the 1980s to process large amounts of data and to
solve complex scientific problems.
Mainframe Computers
Mainframe computers are large-scale computers. These are very
expensive and need a very large clean room with air conditioning, thereby
making them very costly to deploy.
As with supercomputers, mainframes can also support multiple
processors. For example, the IBM S/390 mainframe can support 50,000
users at the same time.
Dumb Terminals
Dumb terminals consist of only a monitor and a keyboard (or mouse).
They do not have their own CPU and memory and use the mainframe
system‘s CPU and storage devices.
Intelligent Terminals
In contrast to dumb terminals, intelligent terminals have their own
processor and thus can perform some processing operations. However,
just like the dumb terminals, they do not have their own storage space.
Minicomputers
As the name suggests, minicomputers are smaller, cheaper, and slower than
mainframes.
They are called minicomputers because they were the smallest computer of their
times.
Also known as midrange computers, the capabilities of minicomputers fall
between mainframe and personal computers.
Minicomputers are widely used in business, education, hospitals, government
organizations, etc.
The first minicomputer was introduced by Digital Equipment Corporation
(DEC) in the mid-1960s. Other manufacturers of minicomputers include IBM
Corporation (AS/400 computers), Data General Corporation, and Prime
Computer.
e-Business
e-Business or electronic business is the process of conducting business via the Internet. This
may include buying and selling of goods and services using computers and the Internet.
Business-to-consumer or B2C: In this form of electronic commerce, business companies
deploy their websites on the Internet to sell their products and services to the customers.
Business-to-business or B2B: This type of electronic commerce involves business
transactions performed between business partners (customers are not involved).
Consumer-to-consumer or C2C: This type of electronic commerce enables
customers to carry business transactions among themselves.
Electronic banking: Electronic banking, also known as Cyber banking or online banking,
supports various banking activities conducted from home, a business, or on the road instead
of a physical bank location.
Bioinformatics
Bioinformatics is the application of computer technology to manage large amount of
biological information.
Computers are used to collect, store, analyse, and integrate biological and genetic information
to facilitate gene-based drug discovery and development.
Bioinformatics is an interdisciplinary field of molecular biology, computer science, statistics,
and mathematics.
Health care
Last few years have seen a massive growth of computers and smartphone users. Like in
our daily lives, computers have also become a necessary device in the health care industry.
The following are areas in which computers are extensively used in the health care industry.
Storing records To begin with, computers are first and foremost used to store the
medical records of patients.
Surgical procedures Computers are used for certain surgical procedures. They enable the
surgeon to use computer to control and move surgical instruments in the patient‘s body for
a variety of surgical procedures.
Better diagnosis and treatment Computers help physicians make better diagnoses and
Remote sensing is the science of taking measurements of the earth using sensors on airplanes
or satellites. These sensors collect data in the form of images, which are then analysed to
derive useful information.
The key feature of remote sensing is that it acquires information about an object without
making physical contact with it. Remote sensing is a sub-field of geography, which can be
applied in the following areas to collect data of dangerous or inaccessible areas for the
following:
• Monitoring deforestation in areas like the Amazon Basin
• Studying features of glaciers in Arctic and Antarctic regions
• Analysing the depth of coastal and ocean areas
• Studying land usage in agriculture
• Examining the health of indigenous plants and crops
• Determining the prospect for minerals
• Locating and measuring intensity of earthquakes by comparing the relative intensity
and precise timings of seismograms collected from different locations
Meteorology
Input: This is the process of entering data and instructions (also known as program) into the
computer system.
The data and instructions can be entered by using different input devices such as keyboard,
mouse, scanner, and trackball.
Storage: Storage is the process of saving data and instructions permanently in the computer
so that they can be used for processing.
The computer storage space not only stores the data and programs that operate on that data
1. CPU (Central Processing Unit): The CPU acts as the brain of the computer, responsible for
executing instructions and performing calculations. It controls and manages the various devices
connected to the system. A faster CPU leads to quicker processing of tasks and improves overall
system performance.
2. Sound Chip: Most modern computers come with a built-in sound chip, which eliminates the need
for a separate sound card unless high-quality audio output is required. A sound chip processes audio
signals and enables basic sound functionality.
3. Modem: A modem, short for modulator-demodulator, is a device that enables a computer to connect
to the internet via a telephone line. It converts digital data from the computer into analog signals that
can be transmitted over phone lines and vice versa.
4. RAM (Random Access Memory): RAM is the computer’s temporary memory used to store data
that is actively being processed by the CPU. More RAM allows the computer to run more applications
simultaneously without slowing down, improving overall system performance.
5. Hard Disk Drive (HDD): The HDD is the computer's long-term storage, used to store data,
documents, and programs permanently. Larger HDDs allow more data to be stored, and while they
don’t affect program execution speed, they influence how quickly files can be accessed by the user.
6. Video Card: The video card, also known as a graphics card, generates and processes images
displayed on the monitor. Modern video cards often have their own dedicated RAM and processor,
enhancing graphics performance. These are particularly useful for high-end gaming or multimedia
tasks.
7. Sound Card: A sound card is an expansion card that enables the computer to process and produce
sound. It allows users to connect audio devices like speakers, microphones, or even stereo systems,
providing richer sound experiences compared to basic onboard sound chips.
1.9 MOTHERBOARD
The motherboard, often referred to as the mainboard or parent board, is the primary component of a
computer, connecting all the hardware components. It is a printed circuit board (PCB) with connectors for
expansion cards, memory modules, and the processor.
Characteristics of a Motherboard:
1. Form Factor: Refers to the size, shape, and layout of the motherboard. It determines compatibility
with different computer cases and the arrangement of components.
2. Chipset: An integrated circuit responsible for coordinating data transfers between the CPU, memory,
and other components. Some modern chipsets include integrated graphics and audio, which can be
disabled if high-performance cards are required.
3. Processor Socket: The socket where the processor (CPU) is installed. The socket type determines
compatibility with various processors. The processor is responsible for executing instructions at a
specified frequency (e.g., 800 MHz means 800 million operations per second). It is typically inserted
into the motherboard using a zero-insertion force (ZIF) socket.
4. Input-Output Connectors: These include various ports for connecting external devices such as USB
ports, serial ports, parallel ports, VGA (for monitors), audio plugs, and Ethernet (RJ45) ports for
networking.
5. Integrated Components:
CMOS Clock and Battery: The CMOS chip stores essential system data, including time and date,
even when the computer is powered off. The chip is powered by a small battery on the motherboard.
BIOS: The Basic Input-Output System (BIOS) is stored in ROM and manages the hardware
settings of the computer. Users can modify the BIOS settings through the BIOS setup interface,
accessible during the system boot process.
System and Expansion Buses: These are pathways that facilitate data transfer between different
components such as memory, processor, and peripherals.
6.Cooling Components:
RAM (Random Access Memory) is used to temporarily store data for fast access while the computer
is running. Unlike a hard disk, RAM is volatile, meaning its contents are erased once the computer is
powered off.
Expansion Slots: These allow users to add additional components such as graphics cards or network
cards. For example, the AGP (Accelerated Graphics Port) slot is used for high-performance graphics
cards.
8.I/O Connectors:
USB Ports: For connecting peripherals like keyboards, mice, and storage devices.
RJ45 (LAN/Ethernet) Port: For networking and internet connectivity.
VGA Connector: For connecting a monitor to the computer.
Audio Jacks: For connecting speakers, headphones, or microphones, interfacing with the integrated
sound card.
KEYBOARD
With a keyboard , the user can type a document, use keystroke shortcuts, access menus, play
games and perform numerous other tasks. Most keyboards have between 80 and 110 keys
which include:
Typing keys
Numeric keys
Function keys
MOUSE
The mouse is the key input device to be used in a graphical user interface (GUI). The
users can use mouse to handle the pointer easily on the screen to perform various
functions like opening a program or file.
With mouse, the users no longer need to memorize commands, which was earlier a
necessity when working with text-based command line environment such as MS-DOS.
Advantages:
Easy to use; Cheap; Can be used to quickly place the cursor anywhere on the screen; Helps
to quickly and easily draw figures; Point and click capabilities makes it unnecessary to
remember certain commands.
Disadvantages:
Needs extra desk space to be placed and moved easily The ball in the mechanical mouse must
be cleaned to remove dust from it.
TRACKBALL
A trackball is a pointing device which is used to control the position of the cursor on the
screen.
These are usually used in notebook and laptop computers where it is placed on the keyboard.
TOUCHPAD
A touchpad (or track pad) is a small, flat, rectangular stationary pointing device with sensitive
surface of 1.5 or 2 inches square.
The user has to slide his finger tips across the surface of the pad to point to a specific object
on the screen. The surface translates the motion and position of user’s fingers to a relative
position on the screen.
There are also buttons around the edge of the pad that work like mouse buttons. Touchpad is
widely used in laptops and is built-in on the keyboard.
Advantages:
Occupies less space.
Easier to use as compared to mouse as its use involves less hands and arms movements.
It is built-in the keyboard, so no need to carry an extra device separately.
Joystick is a cursor control device widely used in computer games and CAD/CAM
applications. It consists of a hand-held lever that pivots on one end and transmits its
coordinates to a computer. It has one or more push-buttons, called switches, whose position
can also be read by the computer.
A stylus is a pen-shaped input device used to enter information or write on the touch screen
of a phone.
Stylus is a small stick that can also be used to draw lines on a surface as input to a computer,
choose an option from a menu, move the cursor to another location on the screen, take notes
and create short messages. The stylus usually slides into a slot built into the smart phone for
A touch screen is a display screen which can identify the occurrence and position of a touch
inside the display region. The user can touch the screen either by his finger or by using a
stylus. These displays can be connected to computers, laptops, PDAs, cell phones etc.
BARCODE READERS
A barcode reader (or price scanner or point-of-sale scanner) is a hand-held input device which
is used to capture and read information stored in a barcode.
A barcode reader consists of a scanner, a decoder, and a cable used to connect the reader with
a computer.
The barcode reader merely captures and translates the barcode into numbers and/or letters.
To make use of the information captured it must be connected to a computer for further
processing. For this purpose, the
barcode reader is connected to a computer through a serial port, keyboard port, or an
interface device called a wedge.
Advantages:
Cheap Portable
Used to read data stored in bar codes Handy and easy to use
IMAGE SCANNER
It is a device that captures images, printed text, handwriting from different sources and
converts it into a digital image for computer editing and display.
Scanners come in hand-held, feed-in, and flatbed types.
In the flat-bed scanner, the object to be scanned is placed on a glass pane and a sensor and
light moves along the pane, reflecting off the image placed on the glass.
A hand image scanner has to be manually moved across an object or image to be scanned.
The scanner produces light from green LEDs which highlight and scan the image onto a
computer for further processing.
Film scanners are usually used in photography and slides. The slide or negative film is
first inserted in strips of six or less frames into the film scanner, and then moved across
a lens and censor to capture the image.
OCR is the process of converting printed materials into text or word processing files that can
be easily edited and stored. The steps involved in OCR include:
Scanning of the text character-by-character
Analyzing the scanned-in image to translate the character image into character codes
(ex ASCII)
Advantages:
Printed documents can be converted into text files.
Advanced OCR can recognize handwritten text and convert them into computer
readable text files.
Disadvantages:
OCR cannot recognize all types of fonts.
Documents that are poorly types or have strikeover cannot be recognized.
Very old documents when passed through OCR may not have an exact copy of the text
file.
Audio Devices
Audio devices are used to either capture or create sound. They enable computers to accept
music, speech or sound affects for recording and/or editing.
Microphone and CD player are examples of two widely used audio input devices.
Microphone feeds audio input to the computer.
The computer must have a sound card to convert analog signals generated through
microphone into digital data so that it can be stored in the computer.
When the user wants to hear the pre-recorded audio input, the sound card converts the
Advantages:
Audio devices can be used by people who have visual problems; It is best used in situations
where users want to avoid i/p through keyboard or mouse.
Disadvantages:
Audio input devices are not suitable in noisy places; With audio input devices it is difficult
to clearly distinguish between two similar sounding words like “sea” and “see”.
PLASMA MONITORS
Plasma monitors are thin and flat monitors widely used in TVs and computers. The
plasma display contains two glass plates that have tiny cells filled with xenon and neon
gas.
The display electrode is covered by a magnesium oxide protective layer and is arranged
in horizontal rows along the screen while the address electrodes are arranged in vertical
columns thereby forming grid like structure.
To ionize the gas in a particular cell, the electrodes that intersect at that cell are charged
at least thousands of times in a small fraction of a second
An electric current begins to flow through the gas in the cell. The current creates
a rapid flow of charged particles thereby stimulating the gas atoms to release
ultraviolet photons.
When these UV photons hit a phosphor atom in the cell, one of the phosphor's electrons
jumps to a higher energy level and the atom heats up. When the electron falls back
to its normal level, it releases energy in the form of a visible light photon.
PROJECTOR
A projector is a device which takes an image from a video source and projects it onto
a screen or other surface.
These days, projectors are used for a wide range of applications varying from home
theater e systems to organizations for projecting information and presentations onto
screens large enough for rooms filled with people to see.
SPEAKERS
Today all business and home users demand sound capabilities and thus different
types of speakers to enable users to enjoy music, movie, or a game and the voice will
be spread through the entire room. With good quality speakers, the voice will also be
audible even to people sitting in another or room or even to neighbors.
However, in case the user wants to enjoy loud music without disturbing the people
around him, he can use a headphone.
Another device called headset was developed to allow the users to talk and listen at the
same time, using the same device.
PRINTERS
Printer is a device that outputs text and graphics information obtained from the computer and
prints it on to a paper. Printers are available in the market in a variety of size, speed,
sophistication, and cost.
The qualities of printer which are of interest to users include:
Color: Colored printouts are needed for presentations or maps and other pages where color
is part of the information. They are more expensive.
Memory: Most printers have a small amount of memory that can be expanded by the user.
Having more memory makes enhances the speed of printing
Resolution: The resolution of a printer means the sharpness of text and images on paper.
It is usually expressed in dots per inch (dpi). Even the least inexpensive printer provides
sufficient resolution for most purposes at 600 dpi.
Speed: Speed means number of pages that are printed in one minute. While high speed
printers are a little expensive, the inexpensive printers on the other hand can print only
about 3 to 6 sheets per minute. Color printing is even slower.
Impact Printer: They create characters by striking an inked ribbon against the paper. Ex.,
dot-matrix printers, daisywheel printers, and most types of line printer.
Non-Impact Printer: Non-impact printers are much quieter than impact printers as their
Advantages
It can produce carbon copies; offers lowest printing cost per page; widely used for bulk
printing where quality of the print is not of much importance; is cheap;
When the ink is about to finish, the printout gradually fades rather than suddenly
stopping partway through a job;
It can use continuous paper rather than individual sheets, making them useful for data
logging.
Disadvantages
It creates a lot of noise when the pins strike the ribbon to the paper. It can only print
lower-resolution graphics, with limited quality
It is very slow
Poor print quality
LINE PRINTER
Line printer is a high speed impact printer in which one typed line is printed at a time. The
speed of a line printer usually varies from 600 to 1200 lines-per-minute or approximately 10
to 20 pages per minute. They are widely used in datacenters and in industrial environments.
Band printer is a commonly used variant of line printers.
Band Printer: A band printer (loop printer) is an impact printer. The set of characters are
permanently embossed on the band and this set cannot be changed unless the band is
replaced. The band itself revolves around hammers that push the paper against the
ribbon, allowing the desired character to be produced on the paper. However, band printers
cannot be used for any graphics printing as the characters are predetermined and cannot be
changed unless the band is changed.
INKJET PRINTERS
In inkjet printers, the print head has several tiny nozzles, also called jets.
As the paper moves past the print head, the nozzles spray ink onto it, forming the characters
and images.
The dots are extremely small (usually between 50 and 60 microns in diameter) and are
positioned very precisely, with resolutions of up to 1440x720 dots per inch (dpi).
There is usually one black ink cartridge and one so-called color cartridge containing ink in
primary pigments (cyan, magenta, and yellow).
While inkjet printers are cheaper than laser printers, they are more expensive to maintain.
The cartridges of inkjet printers
have to be changed more frequently and the special coated paper required to produce high-
quality output is very expensive. So the cost per page of inkjet printers becomes ten times
more expensive than laser printers. Therefore, inkjet printers are not well- suited for high-
volume print jobs.
LASER PRINTER
It is a non-impact printer that works at a very high speed and produces high quality
text and graphics.
It uses the photocopier technology. When a document is sent to the printer, a laser
beam "draws" the document on a drum (which is coated with a photo-conductive
material) using electrical charges.
After the drum is charged, it is rolled in toner (a dry powder type of ink).
The toner sticks to the charged image on the drum.
The toner is transferred onto a piece of paper and fused to the paper with heat and
pressure.
After the document is printed, the electrical charge is removed from the drum and the
excess toner is collected.
While color laser printers are also available in the market but users prefer only
monochrome printers because a color laser printer is up to 10 times more expensive
than a monochrome laser printer.
PLOTTERS
A plotter is used to print vector graphics with a high print quality. They are widely used
In a flatbed plotter, the paper is spread on the flat rectangular surface of the plotter and the
pen is moved over it. Flatbed plotters are less expensive and used in many smaller computing
systems. In this type of plotter, the paper is not moved rather plotting is done by moving an
arm that moves a pen over paper.
Requirements Analysis
In this phase, users‘ expectations are gathered to know why the program/software has to be
built. Then all the gathered requirements are analysed to pen down the scope or the objective
of the overall software product. The functionality, capability, performance, availability of
hardware and software components are all analysed in this phase.
Design
The requirements documented in the previous phase acts as an input to the design phase. In
the design phase, a plan of actions is made before the actual development process could
start. This plan will be followed throughout the development process. Moreover, in the
design phase the core structure of the software/program is broken down into modules. The
solution of the program is then specified for each module in the form of algorithms,
flowcharts, or pseudocodes.
Implementation
In this phase, the designed algorithms are converted into program code using any of the high
level languages. The particular choice of language will depend on the type of program like
whether it is a system or an application program.
This phase is also called construction or code generation phase as the code of the software is
generated in this phase.
Testing
In this phase, all the modules are tested together to ensure that the overall system works
Maintenance
Maintenance and enhancements are on-going activities which are done to cope with newly
discovered problems or new requirements. Such activities may take a long time to complete
as the requirement may call for addition of new code that does not fit the original design or
an extra piece of code required to fix an unforeseen problem. As a general rule, if the cost of
the maintenance phase exceeds 25% of the prior-phases cost then it clearly indicates that the
overall quality of at least one prior phase is poor. In such cases, it is better to re-build the
software (or some modules) before maintenance cost is out of control.
PROGRAMMING PARADIGMS
A programming paradigm is a fundamental style of programming that defines how the
structure and basic elements of a computer program will be built.
The style of writing programs and the set of capabilities and limitations that a particular
programming language has depends on the programming paradigm it supports.
These paradigms, in sequence of their application, can be classified as follows:
Monolithic programming — emphasizes on finding a solution
Procedural programming—lays stress on algorithms
Structured programming—focuses on modules
Object-oriented programming—emphasizes on classes and objects
Logic-oriented programming—focuses on goals
Rule-oriented programming—makes use of ‘if-then-else’ rules for computation
Constraint-oriented programming—utilizes invariant relationships to solve a problem.
PROCEDURAL PROGRAMMING
In procedural languages, a program is divided into subroutines that can access global
data. To avoid repetition of code, each subroutine performs a well-defined task. A
subroutine that needs the service provided by another subroutine can call that
subroutine.
Therefore, with ‘jump’, ‘goto’, and ‘call’ instructions, the sequence of execution of
instructions can be altered. FORTRAN and COBOL are two popular procedural
programming languages
Advantages
o The only goal is to write correct programs
o Programs are easier to write as compared to monolithic programming
Disadvantages
o No concept of reusability
STRUCTURED PROGRAMMING
Structured programming employs a top-down approach in which the overall program
structure is broken down into separate modules. This allows the code to be loaded into
memory more efficiently and also be reused in other programs.
Modules are coded separately and once a module is written and tested individually, it
is then integrated with other modules to form the overall program. Structured
programming is based on modularization which groups related statements together into
modules.
Advantages
• With modules, many programmers can work on a single, large program, with each
working on a different module.
• A structured program takes less time to be written than other programs.
• Modules or procedures written for one program can be reused in other programs as
well.
Disadvantages
Not data-centred
Global data is shared and therefore may inadvertently modified.
Main focus is on functions
Sequence
Sequence means that each step of the algorithm is executed in the specified order. An
algorithm to add two numbers is given in Figure below. This algorithm performs the steps in
a purely sequential order.
Decision
Decision statements are used when the outcome of the process depends on some condition.
For example, if x=y, then print ―EQUAL‖. Hence, the general form of the if construct can
be given as if condition then process. An algorithm to check the equality of two numbers is
shown in Figure below.
Repetition
Repetition, which involves executing one or more steps for a number of times, can be
implemented using constructs such as while, do-while, and for loops. These loops execute
one or more steps until some condition is true. Figure below shows an algorithm that prints
the first 10 natural numbers.
1.11.2 Flowcharts
A flowchart is a graphical or symbolic representation of a process. It is basically used
to design and document virtually complex processes to help the viewers to visualize the logic
of the process, so that they can gain a better understanding of the process and find flaws,
bottlenecks, and other less obvious features within it. When designing a flowchart, each step
in the process is depicted by a different symbol and is associated with a short description.
Symbols of flowchart
Example:
Draw a flowchart to calculate the salary of a daily wager.
Solution
Advantages of Flowcharts
A flowchart is a diagrammatic representation that illustrates the sequence of steps that
must be performed to solve a problem. They are usually drawn in the early stages of
formulating computer solutions to facilitate communication between programmers and
business people.
Flowcharts help programmers to understand the logic of complicated and lengthy
problems.
They help to analyze the problem in a more effective manner.
Flowchart is also used for program documentation.
Flowchart can be used to debug programs that have error(s).
Limitations of using Flowcharts
Drawing flowcharts is a laborious and a time consuming activity.
Flowchart of a complex program becomes, complex and clumsy. At times, a little bit
of alteration in the solution may require complete re-drawing of the flowchart.
Essentials of what is done may get lost in the technical details of how it is done.
There are no well-defined standards that limits the details that must be incorporated in
a flowchart.
1.11.3 PSEUDOCODE
It is a form of structured English that describes algorithms. It facilitates the
designers to focus on the logic of the algorithm without getting bogged down
by the details of language syntax.
Pseudocode is a compact and informal high-level description of an algorithm
that uses the structural conventions of a programming language. It is meant
for human reading rather than machine reading, so it omits the details that are
not essential for humans. Such details include keywords, variable
declarations, system-specific code and subroutines.
It is commonly used in textbooks and scientific publications for documenting
algorithms, and for sketching out the program structure before the actual coding
is done. This would help even the non-programmers to understand the logic of
the designed solution.
There are no standards defined for writing a pseudocode because a
pseudocode is not an executable program. Flowcharts can be considered as a
Variables: hours worked, wages per hour, overtime charges, overtime hrs, salary.
Example: Write a pseudocode for calculating the price of a product after adding sales tax to
its original price.
Solution
1. Read the price of the product
2. Read the sales tax rate
3. Calculate sales tax = price of the item × sales tax rate
4. Calculate total price = price of the product + sales tax
5. Print total price
6. End
Variables: price of the product, sales tax rate, sales tax, total price
Example: Write a pseudocode to read the marks of 10 students. If marks are greater than 50,
the student passes, else the student fails. Count the number of students who pass and the
Types of Errors
Run-time Errors As the name suggests, run-time errors occur when the program is being run
executed. Such errors occur when the program performs some illegal operations like
• Dividing a number by zero
• Opening a file that already exists
• Lack of free memory space
• Finding square or logarithm of negative numbers
Run-time errors may terminate program execution, so the code must be written in such a way
that it handles all sorts of unexpected errors rather terminating it unexpectedly. This ability
to continue operation of a program despite of run-time errors is called robustness.
Compile-time Errors Again as the name implies, compile-errors occur at the time of
compilation of the program. Such errors can be further classified as follows:
Syntax Errors Syntax error is generated when rules of C programming language are violated.
Debugging, on the other hand, is an activity that includes execution testing and code
correction. The main aim of debugging is locating errors in the program code. Once the errors
are located, they are then isolated and fixed to produce an error-free code. Different
approaches applied for debugging a code includes:
Brute-Force Method In this technique, a printout of CPU registers and relevant memory
locations is taken, studied, and documented. It is the least efficient way of debugging a
program and is generally done when all the other methods fail.
Backtracking Method It is a popular technique that is widely used to debug small applications.
It works by locating the first symptom of error and then trace backward across the entire
source code until the real cause of error is detected. However, the main drawback of this
approach is that with increase in number of source code lines, the possible backward paths
become too large to manage.
Cause Elimination In this approach, a list of all possible causes of an error is developed. Then
relevant tests are carried out to eliminate each of them. If some tests indicate that a particular
cause may be responsible for an error then the data are refined to isolate the error.
Let us take a problem, collect its requirement, design the solution, implement it in C and then
test our program.
Problem Statement: To develop an automatic system that accepts marks of a student and
generates his/her grade.
Requirements Analysis: Ask the users to enlist the rules for assigning grades. These rules
are:
Design: In this phase, write an algorithm that gives a solution to the problem.
Step 1: Enter the marks obtained as M
if(marks>=75)
grade = 'O';
else if(marks>=60 && marks<75) grade = 'A';
else if(marks>=50 && marks<60) grade = 'B';
else if(marks>=40 && marks<50) grade = 'C';
else
grade = 'D';
printf("\n GRADE = %c", grade);
}
Test The above program is then tested with different test data to ensure that the program
gives correct output for all relevant and possible inputs. The test cases are shown in the table
given below.
INTRODUCTION TO C
1.13 Introduction
C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories.
C was initially developed for writing system software.
Today, C has become a popular language and various software programs are written using
this language.
Many other commonly used programming languages such as C++ and Java are also based on
C.
1.13.1 Characteristics of C
C is a robust language whose rich set of built-in functions and operators can be used to write
complex programs.
A high level programming language, which enables the programmer to concentrate on
the problem at hand and not to worry about the machine code.
Small size. C has only 32 keywords. This makes it relatively easy to learn as compared
to other languages.
Makes extensive use of function calls.
C is well suited for structured programming. vice versa)
Header Files
● When working with large projects, it is often desirable to make sub-routines and store
them in a different file known as header file. The advantage of header files can be realized
when
a) The programmer wants to use the same subroutines in different programs.
b) The programmer wants to change, or add, subroutines, and have those changes be
reflected in all other programs.
● Conventionally, header files names ends with a ―.h‖ extension and its name can use only
letters, digits, dashes, and underscores.
● While some standard header files are available in C, but the programmer may also create
his own user defined header files
Object Files
Object files are generated by the compiler as a result of processing the source code file. Object
files contain compact binary code of the function definitions. Linker uses this object file to
produce an executable file (.exe file) by combining the of object files together. Object files
have a ―.o‖ extension, although some operating systems including Windows and MS-DOS
have a ―.obj‖ extension for the object file.
A compiler converts a C program into an executable. There are four phases for a C
program to become an executable:
• Pre-processing
• Compilation
• Assembly
• Linking
Pre-processing
This is the first phase through which source code is passed. This phase includes:
1. Removal of Comments
2. Expansion of Macros
3. Expansion of the included files.
4. Conditional compilation
The preprocessed output is stored in the filename.i
1.9 C Tokens
In a passage of text, individual words and punctuation marks are called Tokens.
Similarly, in a C program the smallest individual units are known as C tokens.
C tokens are the basic buildings blocks in C language which are constructed together
Keywords:
keywords are reserved words that have special meanings to the compiler. They
cannot be used as identifiers (like variable names, function names, etc.). These
words are part of the C language syntax.
C has a set of 32 reserved words often known as keywords. All keywords are basically a
sequence of characters that have a fixed meaning. By convention all keywords must be
written in lowercase (small) letters.
Identifiers:
An identifier is the name used to identify variables, functions, arrays,
structures, etc. It is the user-defined name for any program element.
Basic Datatypes in C
The data type defines the type of data stored in a memory location. The data type
determines how much memory should be allocated for a variable. Various types of data
The data types that can be manipulated by machine instructions are called primitive
data types. They are also called basic data types or simple data types or fundamental
data types.
All C compilers supports five fundamental data types, namely integer (int), character
(char), floating point (float), double-precision floating point (double) and void. Many
of them also extended data types such as long int and long double.
void
Integer Types:
Integers are whole numbers with a range of values supported by particular machine.
Generally, integers occupy one word of storage, and since the word sizes of machines vary
(typically, 16 or 32 bits) the size of an integer that can stored depends on the computer.
If we use a 16 bit word length, the size of the integer value is limited to the range - 32768 to
+32767 (that is, -215 to +215 - 1). A signed integer uses one bit for sign and 15 bits for the
magnitude of the number.
In order to provide some control over the range of numbers and storage space, C has three
classes of integer storage, namely short int, int, and long int, in both signed and unsigned
Floating point (or real) numbers are stored in 32-bits (on all 16bit and 32 bit machines), with
6 digits of precision. Floating points numbers are defined in C by the keyword float. When
the accuracy provided by a float number are not sufficient, the type double can be used to
define the number. A double data type number uses 64 bits giving a precision of 14 digits.
These are known as double precision numbers,
The void type has no values. This is usually used to specify the type of functions. The type
of a function is said to be void when it does not return any value to the calling function. It
can also play the role of a generic type, meaning that it can represent any of the other standard
types.
Character Types:
A single character can be defined as a character (char) type data. Characters are usually stored
in 8 bits (one byte) of internal storage. The qualifier signed or unsigned may be explicitly
applied to char. While unsigned chars have values between 0 and 255, signed chars have
values from -128 to 127.
DECLARATION OF VARIABLES
After designing suitable variable names, we must declare them to the compiler. Declaration
does two things:
The declaration of variables must be done before they are used in the program.
A variable can be used to store a value of any data type. That is, the name has nothing to do
with its type. The syntax for declaring a variable is as follows:
Data-type v1,v2,v3,…vn;
v1, v2, v3, …… vn are the names of variables. Variables are separated by commas. A
declaration statement must end with a semicolon. For example, valid declarations are:
int count;
int number, total; double ratio;
int and double are the keywords to represent integer type and real type data values
respectively.
Below shows the various keywords and their equivalents data types:
Another user-defined data type is enumerated data type. The general syntax of enumerated
data type is:
enum identifier {value 1,value 2,...value n};
Here, identifier is a user-defined enumerated data type which can be used to declare
variables that can have one of the values enclosed within the braces. The values inside
the braces are known as enumeration constants. After this declaration, we can declare
variables to be of this 'new' type as: enum identifier v1, v2, ... vn;
The enumerated variables v1, v2, ... vn can only have one of the values value1,
value2, ... valuen. The following kinds of declarations are valid: v1=value5;
v3=value1;
Variables
● A variable is defined as a meaningful name given to the data storage location in
computer memory.
● When using a variable, we actually refer to address of the memory where
thedata is stored. C language supports two basic kinds of variables.
● Numeric variables can be used to store either integer values or floating point values.
● While an integer value is a whole numbers without a fraction part or decimal point, a
Constant
Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals. Constants can be of any of the basic data types
like an integer constant, a floating constant, a character constant, or a string literal.
There are enumeration constants as well.
Octal Integers constant consists of any combination of digits from 0 through 7 with a O at the
beginning. Some examples of octal integers are
int X=O123; // here 0123 is a octal integer constant
Hexadecimal integer constant is preceded by OX or Ox, they may contain alphabets from A
to F or a to f. The alphabets A to F refers to 10 to 15 in decimal digits. Example of valid
hexadecimal integers are
int x=Ox12 // here Ox12 is a Hexa-Decimal integer constant
Real Constants:
Real Constants consists of a fractional part in their representation. Integer constants are
inadequate to represent quantities that vary continuously. These quantities are represented by
numbers containing fractional parts like 26.082. Example of real constants are
float x = 6.3; //here 6.3 is a double constant.
float y = 6.3f; //here 6.3f is a float constant.
float z = 6.3 e + 2; //here 6.3 e + 2 is a exponential constant.
float s = 6.3L ; //here 6.3L is a long double constant
Real Numbers can also be represented by exponential notation. The general form for exponential
notation is mantissa exponent. The mantissa is either a real number expressed in decimal notation or
an integer. The exponent is an integer number with an optional plus or minus sign.
String Constants:
A string constant is a set of characters enclosed in double quotation marks. The characters
in a string constant sequence may be a alphabet, number, special character and blank space.
Example of string constants are
"VISHAL" "1234" "God Bless" "!. ?"
Constant Meaning
'\a' .Audible Alert (Bell)
'\b' .Backspace
'\f' .Form feed
● A stream acts in two ways. It is the source of data as well as the destination of data.
● C programs input data and output data from a stream. Streams are associated with a
physical device such as the monitor or with a file stored on the secondary memory.
● In a text stream, sequence of characters is divided into lines with each line being
terminated with a new-line character (\n). On the other hand, a binary stream contains
data values using their memory representation.
● Although, we can do input/output from the keyboard/monitor or from any file but in this
chapter we will assume that the source of data is the keyboard and destination of the data is
the monitor.
Printf() Function
● The printf function is used to display information required to the user and also
prints the values of the variables. Its syntax can be given as
printf (conversion string‖, variable list);
● The parameter control string is a C string that contains the text that has to be written
on to the standard output device. The prototype of the control string can be given
as below
%[flags][width][.precision][length]specifier
flag description
- Left-justify within the data given field width
+ Displays the data with its numeric sign (either + or -)
Used to provide additional specifiers like o, x, X, 0, 0x or 0X for
# octal and hexa decimal values respectively for values different
than zero.
0 The number is left-padded with zeroes (0) instead of spaces
length Description
h When the argument is a short int or unsigned short int.
Scanf() Function:
● The scanf() is used to read formatted data from the keyboard. The syntax of
the scanf() can be given as,
scanf (―control string‖, arg1, arg2, ................... argn);
● The control string specifies the type and format of the data that has to be
obtained from the keyboard and stored in the memory locations pointed by the
arguments arg1, arg2,…, argn. The prototype of the control string can be give as:
[%[*][width][modifiers]type]
● * is an optional argument that suppresses assignment of the input field. That is,
it indicates that data should be read from the stream but ignored (not stored in
the memory location).
● width is an optional argument that specifies the maximum number of characters
to be read.
● modifiers is an optional argument that can be h, l or L for the data pointed by
the corresponding additional arguments. Modifier h is used for short int or
unsigned short int, l is used for long int, unsigned long int or double values.
Finally, L is used long double data values.
● Type is same as specifier in printf()
● EXAMPLE OF printf() and scanf():
#include<stdio.h>
The ASCII execution character set also includes the following control characters:
New-line character (represented by \n in the source file),
Alert (bell) tone (\a )
Backspace (\b )
Carriage return (\r )
Null character (\0 )