0% found this document useful (0 votes)
2 views75 pages

Module 1- Introduction to C Programming (1)

The document outlines the course 'Principles of Programming using C' at Acharya Institute of Technology, detailing course outcomes, program outcomes, educational objectives, and specific outcomes related to computer science and engineering. It includes a comprehensive introduction to C programming, characteristics of computers, the stored program concept, and the evolution of computer generations from first to fifth. Each generation is described with its hardware technology, memory, software technology, advantages, and disadvantages.

Uploaded by

vishuuvishnu57
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views75 pages

Module 1- Introduction to C Programming (1)

The document outlines the course 'Principles of Programming using C' at Acharya Institute of Technology, detailing course outcomes, program outcomes, educational objectives, and specific outcomes related to computer science and engineering. It includes a comprehensive introduction to C programming, characteristics of computers, the stored program concept, and the evolution of computer generations from first to fifth. Each generation is described with its hardware technology, memory, software technology, advantages, and disadvantages.

Uploaded by

vishuuvishnu57
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

ACHARYA INSTITUTE OF TECHNOLOGY

Soladevanahalli, Bengaluru – 560107

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Principles of Programming using C


(BPOPS203)

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

COs, POs, PEOs, PSOs

COURSE OUTCOMES (COS)


1. Illustrate the basic concepts of computer system and C programming fundamentals.
2. Apply the C programming constructs to solve simple problems.
3. Write C programs using arrays and functions to develop applications.
4. Apply the concepts of strings and pointer in writing the program for data manipulation and
memory management.
5. Write C programs using structures, unions and Enumerated data-types to solve given problems.
6. Implement programs using C constructs, structures, strings, pointers and file I/O operations for
given problems.

PROGRAM OUTCOMES (POS)


1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
2|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions

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

PROGRAM EDUCATIONAL OBJECTIVES (PEOS)

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.

PROGRAM SPECIFIC OUTCOME (PSOS)

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
3|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

CO-PO -PSO Mapping

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
4|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

TABLE OF CONTENTS

Module Module Page Nos


Introduction to C: Introduction to
computers, input and output devices,
designing efficient programs. Introduction
1 to C, Structure of C program, Files used in
a C program, Compilers, Compiling and
executing C programs, variables,
constants, Input/output statements in C.

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.

1.2 Characteristics of Computer:


We have seen that a computer is an electronic device that performs a function based on a
given set of instructions known as a program. A computer accepts data, processes it, and
produces information. These days, computers have become a crucial part of our everyday
lives, and we need computers just like we need televisions, telephones, or other electronic
devices at home.
The important characteristics of a computer (refer to Figure below).

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
5|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
6|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 No IQ: Although the trend today is to make computers intelligent by inducing artificial
intelligence (AI) in them, they still do not have any decision-making abilities of their
own. They need guidance to perform various tasks.
 Economical: Today, computers are considered as short-term investments for
achieving long-term gains. computers also reduces manpower requirements and leads
to an elegant and efficient way of performing various tasks.

Stored Program Concept


All digital computers are based on the principle of stored program concept, which was
introduced by Sir John von Neumann in the late 1940s.
The following are the key characteristic features of this concept:
 Before any data is processed, instructions are read into memory.
 Instructions are stored in the computer’s memory for execution.
 Instructions are stored in binary form (using binary numbers—only 0s and 1s).
 Processing starts with the first instruction in the program, which is copied into a
control unit circuit. The control unit executes the instructions.
 Instructions written by the users are performed sequentially until there is a break
in the current flow.
 Input / Output and processing operations are performed simultaneously. While data
is being read/written, the central processing unit (CPU) executes another program
in the memory that is ready for execution.

Types of Stored Program Computers:


 A computer with a Von Neumann architecture stores data and instructions in the
same memory. There is a serial machine in which data and instructions are selected
one at a time.
 Data and instructions are transferred to and from memory through a shared data
bus. Since there is a single bus to carry data and instructions, process execution
becomes slower.
 Later Harvard University proposed a stored program concept in which there was a
separate memory to store data and instructions. Instructions are selected serially
from the instruction memory and executed in the processor.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
7|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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.

First Generation (1942–1955)


Hardware Technology-First generation computers were manufactured using
thousands of vacuum tubes; a vacuum tube is a device made of fragile glass.
Memory- Electromagnetic relay was used as primary memory and punched
cards were used to store data and instructions.
Softw are Technology- Programming was done in machine or assembly
language.
Used for Scientific applications

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
8|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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.

Second Generation (1955–1964)


Hardware Technology: Second generation computers were manufactured using
transistors (figure). Transistors were reliable, powerful, cheaper, smaller, and

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
9|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
cooler than vacuum tubes.
Memory: Magnetic core memory was used as primary memory; magnetic tapes
and magnetic disks were used to store data and instructions. These computers had
faster and larger memory than the first-generation computers.
Software Technology: Programming was done in high level programming
languages. Batch operating system was used.
Used for Scientific and commercial applications.
Examples Honeywell 400, IBM 7030, CDC 1604, UNIVAC LARC

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
10 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
expensive.

Third Generation (1964–1975)


Hardware Technology- Third generation computers were manufactured using integrated
chips (ICs) (shown in Figure below).

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
11 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 These computers had time sharing operating system which allowed interactive use of
computer by one or more users simultaneously thereby improving the productivity of
the users.

Fourth Generation (1975–1989)


Hardware Technology: Fourth generation computers were manufactured using ICs with LSI
(Large Scale Integrated) and later with VLSI technology (Very Large Scale Integration).
Microcomputers came into existence.
Use of personal computers became widespread. High speed computer networks in the form
of LANs, WANs, and MANs started growing.
Memory: Semiconductor memory was used as primary memory, large capacity magnetic
disks were used as built-in secondary memory. Magnetic tapes and floppy disks were used as
portable storage devices.
Software Technology: Programming was done in high level programming language such
as C and C++. Graphical User Interface (GUI) based operating system (e.g. Windows) was
introduced.
Used for: Scientific, commercial, interactive online, and network applications.
Examples: IBM PC, Apple II, TRS-80, VAX 9000, CRAY-1, CRAY-2, CRAY-X/MP.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
12 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
computers in both office and home became widespread.
 Networks allowed sharing of resources thereby efficient utilization of computer
hardware and software.

Fifth Generation (1989–Present)


Hardware Technology: Fifth generation computers are manufactured using ICs with ULSI
(Ultra Large Scale Integrated) technology. The use of Internet became widespread and very
powerful mainframes, desktops, portable laptops, and smartphones are being used commonly.
Supercomputers use parallel processing techniques.
Memory: Semiconductor memory is used as primary memory; large capacity magnetic disks
are used as built-in secondary memory. Magnetic tapes and floppy disks were used as portable
storage devices, which have now been replaced by optical disks and USB flash drives.
Software Technology: Programming is done in high-level programming languages such as
Java, Python, and C#. Graphical User Interface (GUI)-based operating systems such as
Windows, Unix, Linux, Ubuntu, and Apple Mac are being used.
Used for: Scientific, commercial, interactive online, multimedia (graphics, audio, video),
and network applications.
Examples: IBM notebooks, Pentium PCs, SUM workstations, IBM SP/2, Param
supercomputer.

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
13 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 Air-conditioned rooms required for mainframes and supercomputers but not for
microprocessors

1.5 Classification of Computers


Computers can be broadly classified into four categories based on their speed, amount of data
that they can process, and price (refer to Figure below).
These categories are as follows:
 Supercomputers
 Mainframe computers
 Minicomputers
 Microcomputers

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
14 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 Supercomputers use parallel processing technology and can perform more than one trillion
calculations in a second.
 A single supercomputer can support thousands of users at the same time.
 Such computers are mainly used for weather forecasting, nuclear energy research, aircraft
design, automotive design, online banking, controlling industrial units, etc.
 Some examples of supercomputers are CRAY-1, CRAY-2, Control Data
CYBER 205, and ETA A-10.

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
15 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Microcomputers
 Microcomputers, commonly known as PCs, are very small and cheap. The first
microcomputer was designed by IBM in 1981 and was named IBM-PC.
 Later on, many computer hardware companies copied this design and termed
their microcomputers as PC-compatible, which refers to any PC that is based
on the original IBM PC design.
 Another type of popular PC is designed by Apple. PCs designed by IBM and
other PC- compatible computers have a different architecture from that of
Apple computers.

1.6 Applications of Computers


When the first computers were developed, they were used only in the fields of mathematics
and science. In fact, the first effective utilization of computers was for decoding messages in
military applications. Later on, computers were used in real-time control systems, like for
landing on the moon. However, with the advancement of technology, the cost of computers
and their maintenance declined. Today, computers are widely used in fields such as
engineering, health care, banking, education, etc.
Word processing: Word processing software enables users to read and write documents.
Internet The Internet is a network of networks that connects computers all over the world. It
gives the user access to an enormous amount of information, much more than available in
any library.
Digital video or audio composition: Computers make audio or video composition and

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
16 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
editing very simple.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
17 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
recommend treatments.
Moreover, computers can be used to compare expected results with actual results in order to
help physicians make better decisions.
Doctors sitting in hospitals can monitor their patients sitting in their homes by using
computer-based systems.
As soon as warning signs of serious illnesses are spotted, they alert the concerned
doctor quickly.

Geographic Information System and Remote Sensing


A geographic information system (GIS) is a computer based tool for mapping and analyzing
earth‘s features.
It integrates database operations and statistical analysis to be used with maps. GIS manages
location based information and provides tools for display and analysis of statistics such as
population count, types of vegetation, and economic development opportunities.
Such type of information helps to predict outcomes and plan strategies.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
18 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Meteorology is the study of the atmosphere. This branch of science observes variables of
Earth‘s atmosphere such as temperature, air pressure, water vapour, and the gradients and
interactions of each variable, and how they change over time. Meteorology has applications
in many diverse fields such as the military, energy production, transport, agriculture, and
construction.
Some of the applications include the following:
Weather forecasting: It includes application of science and technology to predict the state of
the atmosphere (temperature, precipitation, etc.) for a future time and a given location.
Aviation meteorology
Aviation meteorology studies the impact of weather on air traffic management. It helps cabin
crews to understand the implications of weather on their flight plan as well as their aircraft.
Agricultural meteorology Agricultural meteorology deals with the study of effects of weather
and climate on plant distribution, crop yield, water-use efficiency, plant and animal
development.
Agricultural meteorology Agricultural meteorology deals with the study of effects of
weather and climate on plant distribution, crop yield, water-use efficiency, plant and animal
development.
Nuclear meteorology Nuclear meteorology studies the distribution of radioactive aerosols
and gases in the atmosphere.
Maritime meteorology Maritime meteorology is the study of air and wave forecasts for ships
operating at sea.

Multi-media and Animation


Multimedia and animation that combines still images, moving images, text, and sound in
meaningful ways is one of most powerful aspects of computer technology. We all have seen
cartoon movies, which are nothing but an example of computer animation.
Other Applications
 Geology
 Astronomy
 Weather Forecasting
 Simulation
 Education
 Online Banking

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
19 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 Industry and Engineering
 Robots
 Decision Support Systems
 Expert Systems

1.7 Basic Organization of a Computer


A computer is an electronic device that performs five major operations:
• Accepting data or instructions (input)
• Storing data
• Processing data
• Displaying results (output)
• Controlling and coordinating all operations inside a computer.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
20 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
but also stores the intermediate results and the final results of processing. A computer has
two types of storage areas:
Primary storage: Primary storage, also known as the main memory , is the
storage area that is directly accessible by the CPU at very high speeds. It is used
to store the data and parts of programs, the intermediate results of processing, and
the recently generated results of jobs that are currently being worked on by the
computer.
Secondary storage:
Also known as auxiliary memory, this memory is just the opposite of primary
memory. It overcomes all the drawbacks of the primary storage area.
It is cheaper, non-volatile, and used to permanently store data and programs
of those jobs that are not being currently executed by the CPU. Secondary
memory supplements the limited storage capacity of the primary memory.
Output: Output is the process of giving the result of data processing to the outside
world (external to the computer system). The results are given through output
devices such as monitor, and printer.
Control Unit: The control unit (CU) is the central nervous system of the entire
computer system. It manages and controls all the components of the computer
system. It is the CU that decides the manner in which instructions will be
executed and operations performed.
Note that the CPU is a combination of the arithmetic logic unit (ALU) and the
CU. The CPU is better known as the brain of the computer system
because the entire processing of data is done in the ALU, and the CU
activates and monitors the operations of other units (such as input, output,
and storage) of the computer system.
Processing: The process of performing operations on the data as per the
instructions specified by the user (program) is called processing. Data and
instructions are taken from the primary memory and transferred to the ALU, which
performs all sorts of calculations.

INSIDE THE COMPUTER

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
21 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
22 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
8. Network Card: The network card enables the computer to connect to local networks or the internet,
especially for high-speed connections such as cable or DSL. It is essential for online communication
and data transfer between computers.
9. Fans: Computers are equipped with fans that help maintain a cool operating temperature by
circulating air inside the system. This prevents overheating of the CPU and other components,
ensuring smooth performance.
10. Cables: Inside the computer, flat, ribbon-like cables are used to transmit power and data between
different components. These cables ensure that each part of the computer, such as the hard drive,
motherboard, and CPU, can communicate and function properly.

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:

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
23 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 Processor Cooling: To prevent overheating, the processor is attached to a heat sink, typically made
from metals like copper or aluminum. A fan is used to ensure proper air circulation around the
processor and other components.

7.RAM and Expansion Slots:

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
24 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

1.8 INPUT DEVICES


An input device is used to feed data and instructions into the computer. In the absence of an
input device, a computer would have only been a display device.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
25 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Advantages: Easy to use and cheap


Disadvantages:
 Keyboard cannot be used to draw figures
 The process of moving the cursor to some other position is very slow. Mouse and
other pointing devices are more apt for this purpose

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
26 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
The trackball is nothing but an upside-down mouse that rotates in place within a socket. The
user rolls the ball to position the cursor at an appropriate position on the screen and then
clicks one of the buttons to select objects or position the cursor for text entry.
Advantages:
Trackball provides better resolution; Occupies less space Easier to use as compared to mouse
as its use involves less hands and arms movements.
Disadvantage:
The trackball chamber is often covered with dust, so it must be cleaned regularly.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
27 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
that purpose.

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
28 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Optical Character Recognition (OCR)

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.

OPTICAL MARK RECOGNITION


OMR is the process of electronically extracting data from marked fields, such as checkboxes
and fill- infields, on printed forms.
The optical mark reader is fed with an OMR sheet to detect the presence of a mark by
measuring reflected light levels.
The OM reader interprets this pattern marks and spaces and stores the interpreted data in
computer for storage, analysis and reporting.
The error rate for OMR technology is less than 1%.
It is used for applications in which large numbers of hand-filled forms have to be quickly
processed with great accuracy, such as surveys, reply cards, questionnaires, ballots or sheets

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
29 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
for multiple choice questions.
Advantages:
 Optical mark readers works with a very fast speed. They can read up to 9,000 forms
per hour
 They are accurate machines with error rates of just 1%

MAGNETIC INK CHARACTER READER (MICR)


MICR is used to verify the legitimacy or originality of paper documents, especially checks.
MICR consists of magnetic ink printed characters which can be recognized by high speed
magnetic recognition devices.
The printed characters provides important information (like check number, bank routing
number, checking account number and in some cases the amount of the check) for processing
to the receiving party.
MICR is widely used to enhance security, speed up the sorting of documents and minimize
the exposure to check fraud.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
30 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
digital data into analog signals and sends it to the speakers.

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

Video Input Devices


Video input devices are used to capture video from the outside world into the computer.
Digital camera is used to capture images or videos. It digitizes the image or video and
stores them on a memory card. The data can the be transferred to the computer using a cable
which connects computer to the digital camera.
Web cameras also capture videos which can be transferred via internet in real time.
Advantages:
 Video input devices are very useful for applications like video conferencing.
 Video input devices can be used to record memorable moments in one‘s life Video
input devices can be used to check security.
Disadvantages:
Videos and images captured using video input devices have a very big file size and there
must be compressed before being stored on the computer.

1.9 OUTPUT DEVICES


Any device that outputs/gives information from a computer is called an output device.
Output devices are electromechanical devices which accept digital data from the computer
and converts them into human understandable language.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
31 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Classification of output devices

SOFT COPY DEVICES


Soft copy output devices are those output devices which produce an electronic version of an
output. For example, a file which is stored on hard disk, CD, pen drive, etc. and is displayed
on the computer screen (monitor).
Features of a soft copy output include:
 The output can be viewed only when the computer is on. The user can easily edit the
soft copy output.
 Soft copy cannot be used by people who do not have a computer. Searching data in a
soft copy is easy and fast.
 Electronic distribution of a soft copy is cheaper. It can be done easily and quickly.

CATHODE RAY TUBE MONITORS


 CRT monitors work by firing charged electrons at a phosphorus film. When electron
hit the phosphor coated screen, it glows thereby enabling the user to see the output.
 In a cathode ray tube, the "cathode" is a heated filament which is placed in a vacuum
created inside a glass "tube." The "ray" is a stream of electrons which comes out from
a heated cathode into the vacuum.
 The focusing anode focuses the stream of electrons to form a tight beam which is
then accelerated by an accelerating anode.
 This tight, high-speed beam of electrons flies through the vacuum in the tube and hits
the flat screen at the other end of the tube.
 This screen is coated with phosphor, which glows when struck by the beam, thereby
displaying the picture which the user sees on the monitor.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
32 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Schematic diagram of a Cathode Ray Tube

LIQUID CRYSTAL DISPLAY MONITORS


 LCD monitor is a thin, flat electronic visual display that uses the light modulating
properties of liquid crystals which do not emit light directly.
 LCD screens are used in a wide range of applications ranging from computer monitors,
television, instrument panels, aircraft cockpit displays, signage, to consumer devices
like such as video players, gaming devices, clocks, watches, calculators, and
telephones.
 Liquid crystal display technology is based on blocking light.
 The LCD consists of two pieces of polarizing filters (or substrates) that contain a
liquid crystal material between them.
 A backlight creates light which is made to pass through the first substrate.
 Simultaneously, the electrical currents cause the liquid crystal molecules to align to
allow varying levels of light to pass through to the second substrate and create the
colors and images are seen on the screen.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
33 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Schematic diagram of a Liquid Crystal Display Monitor

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
34 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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.

HARD COPY OUTPUT DEVICES


Hard copy output devices produces a physical form of output. For example, the content of a
file printed on a paper is a form of hard copy output.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
35 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
printing heads do not strike the paper. They offer better print quality, faster printing and the
ability to create prints that contain sophisticated graphics.
Non-impact printers use either solid or liquid cartridge-based ink which is either sprayed,
dripped or electro statically drawn onto the page. The main types of non- impact printer are:
inkjet, printer, laser printer and thermal printer.

DOT MATRIX PRINTER


A dot matrix printer prints characters and images of all types as a pattern of dots. It has a print
head (or hammer) that consists of pins representing the character or image. The print
head runs back and forth, or in an up and down motion, on the page and prints by striking
an ink-soaked cloth ribbon against the paper, much like the print mechanism on a
typewriter.

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

DAISY WHEEL PRINTER


 Daisy wheel printers use an impact printing technology to generate high-quality output

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
36 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
comparable to typewriters but three times faster.
 The print head of a daisy wheel printer is a circular wheel, about 3 inches in diameter
with arms or spokes. The characters are embossed at the outer end of the arms.
 To print a character, the wheel is rotated in such a way that the character to be printed
is positioned just in front of the printer ribbon.

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
37 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
38 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
to draw maps, in scientific applications and in applications like CAD, CAM and CAE
 A drum plotter is used to draw graphics on a paper that is wrapped around a drum. It
works by rotating the drum back and forth to produce vertical motion. The pen which
is mounted on a carriage is moved across the width of the paper. Hence, the vertical
movement of the paper and the horizontal movement of the pen create the required
design under the control of the computer.

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.

1.10 Design and Implementation of Efficient Programs


The design and development of correct, efficient, and maintainable programs depends on the
approach adopted by the programmer to perform various activities that need to be performed
during the development process. The entire program or software (collection of programs)
development process is divided into a number of phases where each phase performs a well-
defined task. Moreover, the output of one phase provides the input for its subsequent phase.
The phases in software development process (as shown in Figure below) can be summarized
as below:

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
39 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
40 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
well as a whole product. Although individual pieces of codes are already tested by the
programmers in the implementation phase, there is always a chance for bugs to creep in the
program when the individual modules are integrated to form the overall program structure.

Software Deployment, Training, and Support


After the code is tested and the software or the program has been approved by the users, it is
then installed or deployed in the production environment. Software Training and Support is
a crucial phase which is often ignored by most of the developers.

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
41 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
MONOLITHIC PROGRAMMING
 Monolithic programs have just one program module as such programming languages
do not support the concept of subroutines. Therefore, all the actions required to
complete a particular task are embedded within the same application itself. This not
only makes the size of the program large but also makes it difficult to debug and
maintain.
 Programs written using monolithic programming languages consist of global data and
sequential code. The global data can be accessed and modified from any part of the
program.
 Examples are Assembly Language and BASIC

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
42 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
o Requires more time and effort to write programs
o Programs are difficult to maintain
o Global data is shared and therefore may get altered (mistakenly)

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
43 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
OBJECT-ORIENTED PROGRAMMING (OOP)
The object-oriented paradigm is task-based and data-based. In this paradigm, all the relevant
data and tasks are grouped together in entities known as objects. It treats data as a critical
element in the program development and restricts its flow freely around the system.
The striking features of OOP include the following:
• Programs are data centred.
• Programs are divided in terms of objects and not procedures.
• Functions that operate on data are tied together with the data.
• Data is hidden and not accessible by external functions.
• New data and functions can be easily added as and when required.
• Follows a bottom-up approach for problem solving.

1.11 Program Design Tools: Algorithms, Flowcharts, Pseudocodes


1.11.1 Algorithms
In general terms, an algorithm provides a blueprint to writing a program to solve a particular
problem. It is considered to be an effective procedure for solving a problem in a finite number
of steps. That is, a well-defined algorithm always provides an answer, and is guaranteed to
terminate.
Algorithms are mainly used to achieve software re-use. Once we have an idea or a blueprint
of a solution, we can implement it in any high-level language, such as C, C++, Java, and so
on.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
44 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
In order to qualify as an algorithm, a sequence of instructions must possess the following
characteristics:
 Be precise.
 Be unambiguous.
 Not even a single instruction must be repeated infinitely.
 After the algorithm gets terminated, the desired result must be obtained.

Control Structures used in Algorithms


An algorithm has a finite number of steps and some steps may involve decision- making and
repetition. Broadly speaking, an algorithm can employ any of the three control structures,
namely, sequence, decision, and repetition.

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.

Algorithm to add two numbers

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.

Algorithm to test for equality of two numbers

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
45 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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.

Selecting the Most Efficient Algorithm:


Many a times, you may formulate more than one algorithm for a problem. In such cases, you
must always analyse all the alternatives and try to choose the most efficient algorithm.
Analysing an algorithm means determining the amount of resources (such as time and
memory) needed to execute it. Algorithms are generally designed to work with an arbitrary
number of inputs, so the efficiency or complexity of an algorithm is stated in terms of time
and space complexity.
The time complexity of an algorithm is basically the running time of a program as a function
of the input size. Similarly, the space complexity of an algorithm is the amount of computer
memory that is required during the program execution as a function of the input size.

Algorithm to print 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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
46 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
The symbols in the flowchart (refer Figure below) are linked together with arrows to show
the flow of logic in the process.

Symbols of flowchart

The symbols of a flowchart include:


 Start and end symbols are also known as the terminal symbols and are represented as
circles, ovals, or rounded rectangles. Terminal symbols are always the first and the last
symbols in a flowchart.
 Arrows depict the flow of control of the program. They illustrate the exact sequence in
which the instructions are executed.
 Generic processing step, also called as an activity, is represented using a rectangle.
Activities include instructions such as add a to b, save the result. Therefore, a
processing symbol represents arithmetic and data movement instructions. When more
than one process has to be executed simultaneously, they can be placed in the same
processing box. However, their execution will be carried out in the order of their
appearance.
 Input/output symbols are represented using a parallelogram and are used to get inputs
from the users or display the results to them.
 A conditional or decision symbol is represented using a diamond. It is basically
used to depict a Yes/No question or a True/False test. The two arrows coming out of
it, one from the bottom vertex and the other from the right vertex, correspond to Yes
or True, and No or False, respectively. The arrows should always be labelled.
 Labelled connectors are represented by an identifying label inside a circle and are
used in complex or multi-sheet diagrams to substitute for arrows. For each label, the
.‗outflow‘ connector must have one or more ‗inflow‘ connectors.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
47 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Example:
Draw a flowchart to calculate the salary of a daily wager.
Solution

Draw a flowchart to determine the largest of three numbers.


Solution

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
48 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
49 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
graphical alternative to pseudocode, but are more spacious on paper.

Example: Write a pseudocode to calculate the weekly wages of an


employee. The pay depends on wages per hour and the number of hours
worked. Moreover, if the employee has worked for more than 30 hours
then he gets twice the wages per hour, for every extra hour that he has
worked.
1. Read hours worked
2. Read wages per hour
3. Set overtime charges to 0
4. Set overtime hrs to 0
5. If hours worked > 30 then
a. Calculate overtime hrs = hours worked – 30
b. Calculate overtime charges =overtime hrs * (2 * wages per hour)
c. Set hours worked = hours worked -
overtime hrs
ENDIF
Calculate salary = (hours worked * wages per
hour) + overtime charges
6. Display salary
7. End

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
50 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
number who fail.
Solution
1. Set pass to 0
2. Set fail to 0
3. Set no of students to 0
4. WHILE no of students < 10
a. input the marks
b. IF marks >= 50 then Set pass = pass + 1
ELSE
Set fail = fail + 1 ENDIF
ENDWHILE
5. End
Variables: pass, fail, no of students, marks

1.12 TYPES OF ERRORS


While writing programs, very often we get errors in our program. These errors if not removed
will either give erroneous output or will not let the compiler to compile the program. These
errors are broadly classified under four groups as shown in Figure below.

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
51 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
For example, if we write int a: then a syntax error will occur since the correct statement should
be int a;
Semantic Errors Semantic errors are those errors which may comply with rules of the
programming language but are not meaningful to the compiler. For example, if we write, a *
b = c; it does not seem correct. Rather, if written like c = a * b would have been more
meaningful.
Logical Errors Logical errors are errors in the program code that result in unexpected and
undesirable output which is obviously not correct. Such errors are not detected by the
compiler, and programmers must check their code line by line or use a debugger to locate
and rectify the errors. Logical errors occur due to incorrect statements. For example, if you
meant to perform c = a + b; and by mistake you typed c = a * b; then though this statement is
syntactically correct, it is logically wrong.
Linker Errors These errors occur when the linker is not able to find the function definition
for a given prototype. For example, if you write clrscr(); but do not include conio.h then a
linker error will be shown. Similarly, even if you have defined a function display_data() but
while calling if you mistakenly write displaydata() then again a linker error will be generated.

1.12.1 Testing and Debugging Approaches


Testing is an activity that is performed to verify correct behavior of a program. It is
specifically carried out with an intent to find errors. Ideally testing should be conducted at all
stages of program development. However, in the implementation stage, three types of tests
can be conducted:
Unit Tests Unit testing is applied only on a single unit or module to ensure whether it exhibits
the expected behaviour.
Integration Tests These tests are a logical extension of unit tests. In this test, two units that
have already been tested are combined into a component and the interface between them is
tested. The guiding principle is to test combinations of pieces and then gradually expanding
the component to include other modules as well. This process is repeated until all the modules
are tested together. The main focus of integration testing is to identify errors that occur when
the units are combined.
System Tests System testing checks the entire system. For example, if our program code
consists of three modules then each of the module is tested individually using unit tests and
then system test is applied to test this entire system as one system.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
52 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
53 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Step 2: If M > 75 then print ―O‖
Step 3: If M >= 60 and M < 75 then print ―A‖ Step 4: If M >= 50 and M < 60 then print
―B‖
Step 5: If M >= 40 and M < 50 then print ―C‖
else print ―D‖
Step 6: End

Implementation: Write the C program to implement the proposed algorithm.


#include <stdio.h>
int main()
{
int marks; char grade;
printf("\n Enter the marks of the student : ");
scanf("%d", &marks);
if (marks<0 || marks >100)
{
printf("\n Not Possible"); exit(1);
}

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
54 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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)

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
55 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 Stable language.
 Structured language as the code can be organized as a collection of one or more
functions.
 Quick language as a well written C program is likely to be as quick as or quicker than
a program written an any other languages.
 Facilitates low level (bitwise) programming
 Supports pointers to refer computer memory, array, structures and functions.
 C is a core language
 C is a portable language.
 C is an extensible language.
 C is often treated as the second best language for any given programming task.
1.13.2 Uses of C
 C language is primarily used for system programming. The portability, efficiency, the
ability to access specific hardware addresses and low runtime demand on system
resources makes it a good choice for implementing operating systems and embedded
system applications.
 C has been so widely accepted by professionals that compilers, libraries, and
interpreters of other programming languages are often implemented in C.
 For portability and convenience reasons, C is sometimes used as an intermediate
language by implementations of other languages. Example of compilers which use C
this way are BitC, Gambit, the Glasgow Haskell Compiler, Squeak, and Vala.
 C is widely used to implement end-user application
1.14 Structure of a C Program
A C program is composed of pre-processor commands, a global declaration section, and one
or more functions.
The pre-processor directives contain special instructions that indicate how to prepare the
program for compilation. One of the most important and commonly used pre- processor
commands is include which tells the compiler that to execute the program, some information
is needed from the specified header file.
The statements in a C program are written in a logical sequence to perform a specific task.
Execution of a C program begins at the main() function. You can choose any name for the
functions.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
56 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Every program must contain one function that has its name as main(). It is the entry point of
the program. Program can include local variable declaration section which contains the
variable declaration of the form datatype var1;. We write Printf ( ) to print the data onto the
console output. We write Scanf ( ) statement which allows the user to enter the values to the
variables created. If the return type of the main ( ) function is int then we write return 0 at the
end of the main ( ) function.
Note: Scanf ( ) and Printf ( ) formats are at page number 67
/* This is my first program in C */
#include<stdio.h> //Preprocessor directive
void main()
{
printf("\n Welcome to the world of of C ");
}

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
57 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

1.15 Files Used in a C Program


Source code file
The source code file contains the source code of the program. The file extension of any C
source code file is ―.c‖. This file contains C source code that defines the main function and
maybe other functions. The main() is the starting point of execution when you successfully
compile and run the program. A C program in general may include even other source code
files (with the file extension .c).

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.

Binary Executable File


The binary executable file is generated by the linker. The linker links the various object files
to produce a binary file that can be directly executed. On Windows operating system, the
executable files have ―.exe‖ extension.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
58 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
1.16 Compiling And Executing C Programs

 The compilation process in the figure below is done in two steps.


 In the first step, the preprocessor program reads the source file as text,
and produces another text file as output.
 Source code lines which begin with the hash symbol are actually not written
in C but in the preprocessor language.
 The output of the preprocessor is a text file which does not contain any
preprocessor statements.
 This file is ready to be processed by the compiler.
 The linker combines the object file with library routines (supplied with
the compiler) to produce the final executable 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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
59 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Compiling
During this process intermediate compiled file filename.s is generated which contains
assembly level instructions
Assembling
• In this phase the filename.s is taken as input and turned into filename.o by the
assembler. This file contains machine-level instructions.
• At this phase, only existing code is converted into machine language, and the function
calls like printf () are not resolved.
Linking
• This is the final phase in which all the linking of function calls with their definitions is
done. Linker knows where all these functions are implemented.
• The linker combines the object file with library routines (supplied with the compiler)
to produce the final executable file.

1.17 Using Comments


● It is a good programming practice to place some comments in the code to help
the reader understand the code clearly.
● Comments are just a way of explaining what a program does. It is merely an
internal program documentation.
● The compiler ignores the comments when forming the object file. This means
that the comments are non-executable statements.

C supports two types of commenting.


● // is used to comment a single statement. This is known as a line comment. A line
comment can be placed anywhere on the line and it does not require to be
specifically ended as the end of the line automatically ends the line.
● /* is used to comment multiple statements. A /* is ended with */ and all statements
that lie within these characters are commented.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
60 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
to write a C program.
 Each and every smallest individual units in a C program are known as C tokens.

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
61 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 These are user- defined names and consist of a sequence of letters and digits,
with a letter as a first character. Both uppercase and lowercase letters are
permitted, although lowercase letters are commonly used. The underscore
character is also permitted in identifiers. It is usually used as a link between
two words in long identifiers.
Rules for Identifiers:

1. Can only contain letters, digits, and underscores


Identifiers may use uppercase and lowercase letters (A–Z, a–z), digits (0–9), and the
underscore (_) character.
Example: total_1, sum2025
2. Must begin with a letter or an underscore
Identifiers cannot begin with a digit.
Valid: value1, _temp
Invalid: 1value
3. Cannot use C keywords
Keywords like int, return, float, etc., are reserved by the language and cannot be used
as identifiers.
Invalid: while, if, main (as a variable)
4. Case-sensitive
C treats uppercase and lowercase letters as different, so value, Value, and VALUE
are considered three different identifiers.
5. No special characters or spaces allowed
Identifiers cannot include symbols like @, #, -, . or spaces.
Invalid: user-name, total amount
6. Should be meaningful (recommended practice)
Use clear and descriptive names that reflect the purpose of the variable or function.
Good: marks, studentAge
Not recommended: x, a1
7. No strict length limit (but avoid very long names)
ANSI C considers only the first 31 characters significant in an identifier. Most
modern compilers support longer names, but it's best to keep them reasonably short
and readable.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
62 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
such as integer constant, floating point constant, character constant etc. can be stored in
memory during execution of a program. The data types in C language are classified mainly
into three groups:

 Primitive data types or Primary Data types or Fundamental Data Types


 Derived data types
 User-defined data types

Primitive data types or Primary Data types or Fundamental Data Types

 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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
63 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
forms. Table below shows all the allowed combinations of basic types and qualifiers and their
size and range on a 16-bit machine.

Floating Point Types:

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,

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
64 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Void Types:

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:

1. It tells the compiler what the variable name is.


2. It specifies what type of data the variable will hold.

The declaration of variables must be done before they are used in the program.

Primary Type Declaration:

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:

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
65 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 int - an integer; reflects size of integers on host machine
 float - single-precision floating point
 double - double-precision floating point
 char - character, a single byte
 unsigned char - Unsigned character
 signed short int - Signed short integer
 signed long int - Signed Long integer
 unsigned int - Unsigned integer
 unsigned short int - Unsigned Short Integer
 unsigned long int - Unsigned Long Integer
 long double - Extended double-precision floating point

Data Size (in


Range
Type Bytes)
char 1 byte -128 to 127 (signed) / 0 to 255 (unsigned)
int 2 bytes -32,768 to 32,767 (signed) / 0 to 65,535 (unsigned)
float 4 bytes ~3.4e-38 to 3.4e+38 (6 digits precision)
double 8 bytes ~1.7e-308 to 1.7e+308 (15 digits precision)
long int 4 bytes -2,147,483,648 to 2,147,483,647
short int 2 bytes Same as int: -32,768 to 32,767
Depends on the base type used (unsigned int, unsigned char,
unsigned Varies
etc.)

USER-DEFINED TYPE DECLARATION

 In C programming, a feature known as "type definition" is available which allows a


programmer to define an identifier that represents an existing data type. The user
defined identifier can be used later in the program to declare variables.
 The general syntax of declaring a variable by user-defined type declaration is:
typedef type identifier;

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
66 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 Here, type is an existing data type and identifier is the "new name" given to the data
type. Here, the new type is 'new' only in name but not the data type.
 Consider the example: typedef int age; typedef float weight;
 Here, age represents int and weight represent float which can be used later in the
program to declare variables as follows:
 age boy1,boy2; weight b1,b2;
 Here, boy1 and boy2 are declared as as integer data type and b1 & b2 are declared as
floating integer data type.
 The main advantage of using user-defined type declaration is that we can create
meaningful data type names for increasing the readability of a program.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
67 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
floating point number, can have a decimal point in them.
● Numeric values may also be associated with modifiers like short, long, signed and
unsigned.
● By default, C automatically a numeric variable signed.
● Character variables can include any letter from the alphabet or from the ASCII chart
and numbers 0 – 9 that are put between single quotes.

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.

Figure: Basic Types of Constants


Integer Constants:
An integer constant is a sequence of digits from 0 to 9 without decimal points or
fractional part or any other symbols. There are 3 types of integers namely decimal integer,
octal integers and hexadecimal integer.

Decimal Integers consists of a set of digits 0 to 9 preceded by an optional + or - sign.


Embedded spaces, commas and non-digit characters are not permitted between digits.
Example for valid decimal integer constants are:
int y=123; //here 123 is a decimal integer constant
int n = -321; // Is valid constant
int m = 15 750; // Illegal numbers. Because space is not allowed.

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
68 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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.

Single Character Constants:


A Single Character constant represent a single character which is enclosed in a pair
of quotation symbols.
Example for character constants are
char p ='ok' ; // p will hold the value 'O' and k will be omitted
char y ='u'; // y will hold the value 'u'
char k ='34' ; // k will hold the value '3, and '4' will be omitted
char e =' '; // e will hold the value ' ' , a blank space
chars ='\45'; // swill hold the value ' ' , a blank space
All character constants have an equivalent integer value which are called ASCII Values.

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" "!. ?"

Backslash Character Constants [Escape Sequences]:


Backslash character constants are special characters used in output functions. Although they
contain two characters they represent only one character. Given belowis the table of escape
sequence and their meanings.

Constant Meaning
'\a' .Audible Alert (Bell)
'\b' .Backspace
'\f' .Form feed

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
69 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
'\n' .New Line
'\r' .Carriage Return
'\t' .Horizontal tab
'\v' .Vertical Tab
'\'' .Single Quote
'\"' .Double Quote
'\?' .Question Mark
'\\' .Back Slash
'\0' .Null
Note that each one of them represents one character, although they consist of two
characters. These characters combinations are known as escape sequences.

Rules that needs to be applied to a #define statement which defines a constant.


● Constant names are usually written in capital letters to visually distinguish them
from other variable names which are normally written in lower case characters. Note
that this is just a convention and not a rule.
● No blank spaces are permitted in between the # symbol and define keyword
● Blank space must be used between #define and constant name and between constant
name and constant value
● #define is a pre-processor compiler directive and not a statement. Therefore, it does not
end with a semi-colon.

Input and Output Statements in C

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

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
70 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Monitor Input Text Stream

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.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
71 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
When the argument is a long int or unsigned long int for
l
integer specifiers.
When the argument is a long double (used for floating point
L
specifiers)

specifier Qualifying Input


c For single character
d For decimal values
F For floating point numbers
E, e Floating point numbers in exponential format
G, G Floating point numbers in the shorter of e format
o For Octal number.
s For a sequence of (string of) characters
u For Unsigned decimal value
x,X For Hexadecimal value.

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>

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
72 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
int main ( )
{
int a;
char c;
printf(“Enter the int and char value\n”);
scanf(“%d%c”,&a,&c);
printf(“a=%d, c=%c”,a,c);
return 0;
}

Input: Enter the int and char value


10 b
a=10, c=b
Character Set in C
The character that can be used to form words, numbers and expressions depend upon
the computer on which the program is run. However, a subset of characters is available
that can be used on most personal, micro, mini and mainframe computers. The characters
in C are grouped into the following categories:
1. Letters
2. Digits
3. Special Characters
4. White spaces
Most ANSI-compatible C compilers accept the following ASCII characters for both the
source and execution character sets. Each ASCII character corresponds to a numeric value.
The ASCII characters and their numeric values.
 The 26 lowercase Roman characters:
abcdefghijklmnopqrstuvwxyz
 The 26 uppercase Roman characters:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
 The 10 decimal digits:
0123456789
 The 30 graphic characters:
!#%^&*()-_=+~'":;?/|\{}[]
, . < > $ Five white space characters:
Space ()
Horizontal tab (\t)
Form feed (\f)
Vertical tab (\v)
New-line character (\n)

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
73 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

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 )

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
74 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
75 | P a g e

You might also like