0% found this document useful (0 votes)
47 views46 pages

Besck204c Module-1

The document provides an introduction to computers, detailing their characteristics, stored program concepts, and historical development across five generations. It classifies computers into supercomputers, mainframes, mini computers, and microcomputers, highlighting their applications in various fields such as healthcare, engineering, and e-business. Additionally, it discusses the evolution of computer technology and its impact on society.

Uploaded by

mayurgawade1616
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)
47 views46 pages

Besck204c Module-1

The document provides an introduction to computers, detailing their characteristics, stored program concepts, and historical development across five generations. It classifies computers into supercomputers, mainframes, mini computers, and microcomputers, highlighting their applications in various fields such as healthcare, engineering, and e-business. Additionally, it discusses the evolution of computer technology and its impact on society.

Uploaded by

mayurgawade1616
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/ 46

Introduction to C Programming BESCK204C

Introduction to C Programming
MODULE-1

CHAPTER-1
INTRODUCTION TO COMPUTERS

[1.1] COMPUTER

“A computer is a machine that takes instructions and performs computations based on


those instructions.”

[1.2] CHARACTERISTICS OF COMPUTERS:

The important characteristics of computer are as follows:

i. Speed:
★ Computers can perform millions of operations per second.
★ The speed of computers is usually given in nanoseconds and picoseconds.
➢ Where 1 nanosecond= 1 x 10-9 and 1 picosecond = 1x 10-12

ii. Accuracy:
★ A Computer is very fast, reliable and robust electronic device.
★ It always gives correct results, provided correct data and a set of instructions are input.
★ The output generated by the computer depends on the given instructions and input data. If the
input data is wrong then the output will also have errors. (garbage-in and garbage out or GIGO)

iii. Automation:
★ Computers are automatable devices that can perform a task without any user intervention.
★ The user just needs to assign the task to the computer after which it automatically controls different
devices attached to it and executes the program instructions.

iv. Diligence:
★ Computers never get tired of repetitive tasks.
★ It can continuously work for hours without creating errors.
★ Even if a large number of executions need to be executed, each and every execution requires the
same duration and is executed with the same accuracy.

v. Versatile:
★ Computers are used in daily life in all fields, for example, they are used as personal computers,
for business-oriented tasks, weather forecasting etc.
★ Therefore, computers are versatile devices as they can perform multiple tasks of different nature
at the same time. For ex: on personal computers used at home you can play games or send emails
or even listen to music.

vi. Memory:
★ Computers have internal or primary memory as well as external or secondary memory.

1
Introduction to C Programming BESCK204C
Introduction to C Programming
★ Computer stores large amount of data and programs in the secondary storage space. The stored
programs can be used whenever required.
★ Internal memory of computers is very expensive and limited in size, secondary storage is cheaper
and of bigger capacity.
★ When data and programs are to be used, they are copied from the secondary memory into the
primary memory (RAM).

vii. No IQ:
★ Trend today is to make computers intelligent by inducing AI(Artificial Intelligence) in them.
★ They still do not have any decision-making abilities of their own. They need guidance to perform
various tasks.

viii. Economical:
★ Computers are considered as short-term investments for long-term gains.
★ Using computers also reduces manpower requirements and leads to efficient way of performing
various tasks. Hence computers save time, energy and money.
★ Computers can do more work in less time.

[1.3] STORED PROGRAM CONCEPT:


Features:
★ 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.
★ Processing starts with the first instruction in the program, which is copied into a control unit
circuit.
★ 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.

Types of Stored Program Concepts:


➔ Computer with Von Neumann Architecture(fig 1.29(a)) 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 rae transferred to and from the memory through shared data.
➔ Processing becomes slower as there only one single bus to carry data and instructions.

➔ Harvard University (fig 1.2(b)) 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 processor.
➔ When instruction needs data, it is selected from the data memory and since there are separate memories,
execution becomes faster.

2
Introduction to C Programming BESCK204C
Introduction to C Programming

[1.4] HISTORY OF COMPUTERS

★ First Generation (1942-1955)


Hardware Technology:
manufactured using thousands of vacuum tubes
Memory:
electromagnetic relay was used as primary memory and punched cards were used to store data
and instructions.
Software Technology:
machine language
Used for: scientific applications
Examples:
ENIAC, EDVAC, EDSAC, UNIVAC
Highlights: Fastest calculating device

★ Second Generation (1955-1964)


Hardware Technology:
manufactured using transistors
Memory:
magnetic core memory; magnetic tapes; magnetic disks were used to store data and
instructions.
Software Technology:
high level programming languages. (Batch OS was used)
Used for: scientific and commercial applications
3
Introduction to C Programming BESCK204C
Introduction to C Programming
Examples:
Honeywell 400, IBM 7030, CDC 1604
Highlights:
Faster, smaller, cheaper and easier to use than first generation computers.

★ Third Generation (1964-1975)


Hardware Technology:
manufactured using integrated chips (IC’s). Minicomputers came into existence.
Memory:
large magnetic core memory; large capacity magnetic tapes; magnetic disks were used to store
data and instructions.
Software Technology:
high level programming languages- pascal etc. (Time sharing OS was used)
Used for: scientific, commercial and interactive online applications
Examples:
IBM 360/370, PDP-8, PADP-11, CDC6600
Highlights:
Faster, smaller, cheaper and easier to use than second generation computers.

★ Fourth Generation (1975-1989)


Hardware Technology:
manufactured using integrated chips (IC’s) with large scale integrated and later with
VLSI technology. Microcomputers came into existence.
Memory:
semiconductor memory; large capacity magnetic disks(for secondary memory) and magnetic
tapes and floppy disks were used.
Software Technology:
high level programming languages-C and C++, GUI, UNIX
Used for: scientific, commercial, interactive online and network applications
Examples:
IBM PC, Apple II, CRAY-I, CRAY-II
Highlights:
Faster, smaller, cheaper, powerful, reliable and easier to use than previous generation
computers.

★ Fifth Generation (1989-present)


4
Introduction to C Programming BESCK204C
Introduction to C Programming
HardwareTechnology
manufactured using integrated chips (IC’s) with ultra large scale integrated and later
with VLSI technology. Use of internet became widespread and very powerful mainframes,
desktops, smartphones, portable laptops.
Memory:
semiconductor memory; large capacity magnetic disks(for secondary memory) and
magnetic tapes and floppy disks were used as portable storage devices.(now replaced with USB
flash drives)
Software Technology:
high level programming languages-JAVA, Python GUI, UNIX, LINUX, Ubuntu Apple Mac
Used for: scientific, commercial, interactive online, network and multimedia (graphics, audio-
video)applications
Examples:
IBM Notebook, Pentium PC’s etc..
Highlights:
Faster, smaller, cheaper, powerful, reliable and easier to use than previous generation
computers.

[1.5] CLASSIFICATION OF COMPUTERS

Computers can be broadly classified into four categories based on their speed, amount of data that
theycan process. and price (refer to Figure)

SUPERCOMPUTERS:
➔ The supercomputer is the fastest, most powerful, and most expensive computer.
➔ Supercomputers were first developed to process large amounts of data and to solve complex
scientific problems.
➔ Supercomputers use parallel processing technology and can perform more than one trillion
5
Introduction to C Programming BESCK204C
Introduction to C Programming
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-I CRAY-2, Control Data CYBER 205, and ETA
A-10.

MAINFRAME COMPUTERS:
➔ Mainframe computers are large-scale computers (but smaller than supercomputers).
➔ 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. Users can
access mainframes by either using terminals or via PCs.
➔ The two types of terminals that can be used with mainframe systems are as follows.

DUMB TERMINAL
● 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 TERMINAL
● 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.
● Usually, PCs are used as intelligent terminals to facilitate data access and other
Services from the mainframe system
● Mainframe computers are typically used as servers on the World Wide Web. They are
also used in organizations such as banks, airline companies, and universities, where a
large number or users frequently access the data stored in their databases.

MINI COMPUTERS:
➔ Minicomputers are smaller, cheaper and slower than mainframes.
➔ They are also called as midrange computers as their capabilities fall between mainframe and
personal computers.
➔ They are widely used in business, education, hospitals, government organizations etc.
➔ First minicomputer was Digital Equipment Corporation (DEC).

MICRO COMPUTERS:
➔ Microcomputers, commonly known as PC’s and are very small and cheap.
➔ They can be classified into following categories.

Desktop PC’s
6
Introduction to C Programming BESCK204C
Introduction to C Programming
• Most popular model of PC’s
• The system unit of desktop PC can be placed flat on desk or table.
• It is widely used in homes and offices.

Laptops
• Laptops are small microcomputers and are very handy and can easily be carried from
one place to another.
• Laptops operate on battery and do not always have to be plugged in like desktop
computers
• Memory and storage capacity is almost equivalent to that of desktop computer.
• Laptops also have hard disk drives, USB drives etc.
• Laptops are generally expensive and are very popular among business travelers.

Workstations
• These are single user computers that have same features like PC’s, but processing speed
matches that of mini or mainframe computers.
• They have advanced processors with more RAM and storage capacity.
• They are more expensive and powerful than any desktop computer.
• They are used by scientists, engineers, graphic designers and can also be used as
servers in a networked environment.

Network Computers
• They have less processing power, memory and storage.
• Specifically designed to access only the internet and are called as Internet PC’s.
• Some computers can be used in home and are connected to television, which serves as
output device.
• Ex: Web-TV
• They are cheaper to purchase and maintain than PC’s

Handheld computers
• Small personal computing devices are commonly known as handheld devices.
• They are small and hence they have small-sized screens and keyboards.
• Examples are Smartphones and Tablet PC’s
o Smartphones
▪ Web enabled telephones
▪ Facilitates user to access internet and send e-mails etc.
▪ They run on advanced operating system that enables it to run various
applications.
▪They also have CPU, more storage space, more memory and large screen
than regular phone.
o Tablet PC’s
▪ A computing device that is smaller than laptop but bigger than
smartphone.
7
Introduction to C Programming BESCK204C
Introduction to C Programming
▪ User-friendly interface, portability and touch screen and have made
tablet popular.
▪ Uses are : view presentations, watching movies, playing games, editing a
document, exchanging documents, taking notes, etc.

[1.6] APPLICATIONS OF COMPUTERS

• When the first computers were developed, they were used only in the fields of mathematics and
science.
• 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.
✓ Users can also add images, tables, and graphs for illustrating a concept.
✓ The software automatically corrects spelling mistakes and includes copy—paste features
(which is very useful where the same text has to be repeated several times).

❖ Internet
✓ The Internet is a network of connects computers all over the world. It gives the user access to
an enormous amount of information, much more than available in any library.
✓ Using e-mail, the user can communicate in seconds with a person who is locate thousands of
miles away. Chat software enables users to chat with another person in real-time. Video
conferencing tools are becoming popular for conducting meetings with people who are
unable to be present at a particular place.

❖ Digital video or audio composition


✓ Computers make audio or video composition and editing very simple. This has drastically
reduced the cost of equipment to compose music or make a film.
✓ Graphics engineers use computers for developing short or full-length films and creating 3-D
models and special effects in science fiction and action movies.

❖ Desktop publishing
Desktop publishing Desktop publishing software enables us to create page layouts for
entire books.

❖ 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. Use
of email and videoconferencing technology has revolutionized the way business is being
conducted these days.

8
Introduction to C Programming BESCK204C
Introduction to C Programming

❖ Bioinformatics
Bioinformatics is the application of computer to manage large amount of biological
information.
✓ Computers are used to collect, store, analyse, biological and genetic information to
facilitate drug discovery and development.
✓ Bioinformatics is an interdisciplinary field of molecular biology, Computer science,
statistics, and mathematics. It involves analyses of genomic information to understand
human diseases and thus discover new drugs to treat those diseases.

❖ Health care
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. Earlier, patient records were kept on paper, with separate records dealing
with different medical issues from separate healthcare organizations.
✓ 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
recommend treatments. Moreover, computers can be used to compare expected results with
actual results in order to help physicians make better decisions.

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

❖ Meteorology
✓ 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.
✓ 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 is impact of weather on air traffic
9
Introduction to C Programming BESCK204C
Introduction to C Programming
management. It helps cabin crews to understand the implications 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.
✓ 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.

❖ Multimedia 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.
❖ Legal System
✓ Computers are used by lawyers to shorten the time required to conduct legal
precedent and case research.
✓ Lawyers use computers to look through millions of individual cases and find
whether similar or parallel cases have been approved, denied, criticized, or overruled
in the past.
✓ This enables the lawyers to formulate strategies based on past case decisions.
Moreover, computers are also used to best track of appointments and prepare legal
documents me for filling cases.

❖ Retail Business
Computers are used in retail shops to enter orders, calculate costs, and print receipts. They
are also used to keep an inventory of the products available and their complete description.

❖ Sports
In sports, computers are used to compile statistics, identify weak players and strong
players by analysing statistics, sell tickets, create training programs and diets for athletes, and
suggest game plan strategies based on the competitor’s past performance.
Computers are also used to generate most of the graphic art displays flashed on
scoreboards.
❖ Travel and Tourism
Computers are used to prepare tickets, monitor the train's or airplane’s route and guide the
plane to a safe landing. They are also used to research about hotels in an area, reserve rooms, or
to rent a car.

❖ Simulation
Supercomputers that can process enormous amount of data are widely used in simulation
10
Introduction to C Programming BESCK204C
Introduction to C Programming
tests. Simulation of automobile crashes or airplane emergency landings is done to identify
potential weakness in designs without risking human lives.
Astronauts are trained using computer-simulated problems that could be encountered
during launch, in space, or upon return on earth.

❖ Astronomy
Spacecrafts are usually monitored using computers that not only keep a continuous record
of the voyage and of the speed, direction, fuel, and temperature, but also suggest corrective action
if the vehicle makes a mistake. With the help of computers, all this is done within a fraction of a
second.

❖ Education
A computer is a powerful teaching aid and can act as another teacher in the classroom.
Teachers use computers to develop instructional material. Teachers may use pictures, graphs, and
graphical presentations to easily illustrate an otherwise difficult concept.

❖ Industry and Engineering


Computers are found in all kinds of industries, such as thermal power plants, oil refineries,
and chemical industries, for process control, computer-aided designing (CAD), and computer-
aided manufacturing (CAM).

❖ Robotics
Robots are computer-controlled machines mainly used in the manufacturing process in
extreme conditions where humans cannot work.

❖ Decision Support Systems


Computers help managers to analyse their organization’s data to understand the present
scenario of their business, view the trends in the market, and predict the future of their products.
Managers also use decision support systems to analyse market research data, to size up the
competition, and to plan effective strategies for penetrating their markets.

❖ Expert Systems
Expert systems are used to automate the decision-making process in a specific area, such
as analyzing the credit histories for loan approval and diagnosing a patient’s condition for
prescribing an appropriate treatment.
Expert systems analyze the available data in depth to recommend a course of action. A
medical expert system might provide the most likely diagnosis of patient’s condition.

[1.7] BASIC ORGANIZATION OF COMPUTER

11
Introduction to C Programming BESCK204C
Introduction to C Programming

A computer is an electronic device which basically performs five major operations which
includes:
1) accepts data or instructions (input)
2) stores data
3) process data
4) displays results (output) and
5) controls and coordinates all operations inside a computer

Figure , which shows the interaction between the different units of the computer system.

INPUT:
★ This is the process of entering data and instructions (also known as programs) into the computer
system.
★ The data and instructions can be entered by using different input devices such as the keyboard,
mouse, scanner, and trackball.
★ Note that computers understand binary language. which consists of only two symbols 0 and 1, so
it is the responsibility of the input devices to convert the input data into binary codes

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 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 man 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 lobs that are currently being worked on by the
computer.
12
Introduction to C Programming BESCK204C
Introduction to C Programming
● Primary storage space is very expensive and therefore limited in capacity.
● Main memory is volatile in nature: that is, as soon as the computer is switched off. the
information stored gets erased. Hence. it cannot be used as a permanent storage of useful
data and programs for future use.
● An example of primary storage is Random Access Memory (RAM).

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 or those jobs
that are not being currently executed by the CPU.
● Secondary memory supplements the limited storage capacity of the primary memory.
● An example is the magnetic disk used to store data, such as C and D drives for future use

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 printers.
★ Since the computer accepts data only in binary form and the result of processing is also in binary
form. the result cannot be directly given to the user.
★ The output devices, therefore, convert the results available in binary codes into a human-readable
language before displaying it to the user.

CONTROL
★ The control unit (CU) 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. It takes care of the step-by-step processing of all operations that are performed on the
computer.
★ 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 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.
★ The intermediate results of processing may be stored in the main memory, as they might be
required again. When the processing completes, the final result is then transferred to the main
memory.
★ Hence. the data might move from main memory to the ALU multiple times before the processing
13
Introduction to C Programming BESCK204C
Introduction to C Programming
is over.

14
Introduction to C Programming BESCK204C
Introduction to C Programming
CHAPTER-2
INPUT AND OUTPUT DEVICES

[2.1] INPUT DEVICES


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

Keyboard
• the keyboard is the main input device for computers
• Computer keyboards look very similar to the keyboards of typewriters, with some additional
keys.
• Using a keyboard, the user can type a document, use keystroke shortcuts. access menus. plav
games and perform numerous other tasks.
• Most keyboards have between 80 and 110 keys, which include the following:
o Typing keys These include the letters of the alphabet. The layout of the keyboard is
known as QWERTY for its first six letters. The QWERTY pattern has been a standard
right from the time computer keyboards were introduced
o Numeric keys These include a set of keys, arranged in the same configuration found on
calculators to speed up data entry of numbers. When the Num Lock key is set to ON, the
user can type numbers, dot, or input the symbols, *, -, and +. When the Num Lock kev is
set to OFF. the numeric keys can be used to move the cursor on the screen.
o Function keys These are used by applications and operating systems to input specific
commands. They are often placed on the top of the keyboard in a single row. Function
Keys can be programmed so that their functionality varies from one program to another.
o Control kevs These are used to handle control of the cursor and the screen. Four arrow
keys are arranged in an inverted T-type fashion between the typing and the numeric kevs.
and are used to move the cursor on the screen in small increments.

Pointing Devices:
A pointing input device enables the users to easily control the movement of the pointer to select
items on a display screen, to select commands from the commands menu, to draw graphics, etc.
Some examples of pointing devices include mouse, trackball, light pen, joystick, and touchpad.

15
Introduction to C Programming BESCK204C
Introduction to C Programming
Mouse:
• It is the key input device used in a graphical user interface (GUI).
• It can be used to handle the pointer easily on the screen to perform various functions such
as opening a program or file.
• With the mouse, the users no longer need to memorize commands, which was earlier a
necessity when working with text-based command line environments like MS-DOS.
• The mouse has two buttons and a scroll wheel. It can be held in the hand and easily moved,
without lifting, along a hard flat surface to move the cursor to the desired location—up,
down, left, or right.
• Once the mouse is placed at the appropriate position, the user may perform the following
operations:
o Point :Placing the pointer over the word or the object on the screen by moving the
mouse on the desk is termed as pointing.
o Click: Pressing either the left or the right button of the mouse is known as clicking.
Clicking a mouse button initiates some action; for example, when you click the
right button by pointing the mouse on a word, a menu pops up on the screen.
o Drag: Dragging means pointing to a desired location while pressing the left
button.
o Scroll: The scroll wheel, which is placed in between the left and right buttons of
the mouse, is used to vertically scroll through long documents.

Trackball
• To move the pointer, the ball is rotated with the thumb, fingers, or the palm of the hand.
• The advantage of a trackball over a mouse is that the former is stationary, and so it does
not require much space to use.
• Moreover, individual trackballs can be placed on any type of surface, including the
user’s lap.
• These advantages make trackballs very popular pointing devices for portable computers
and mobile phones.

Touchpad
• A touchpad (or trackpad) is a small, flat, rectangular stationary pointing device with a
sensitive surface of 1.5—2 square inches.
• The user has to slide his or her fingertips across the surface of the pad to point to a
specific object on the screen.
• The surface translates the motion and position of the user’s fingers to a relative position
on the screen.

Optical Devices:
Optical devices also known as data-scanning devices, use light as a source of input to detect
objects. These devices convert objects into digital data and send it to the computer for further
processing.
Barcode Reader:
• Is a handheld input device that is used to capture and read information stored in a
barcode.
• Function of a barcode reader is to capture and translate barcodes into numerals or letters.
• Barcodes are widely used in the following areas.
o Generate bills in supermarkets
o Check out books from the library.

16
Introduction to C Programming BESCK204C
Introduction to C Programming
o Keep track of employee login
o Identify hospital patients
• Advantages:
o Inexpensive
o Portable
o Handy and easy to use

Image Scanner:
• Is a device that captures images, printed text and handwriting from different sources
such as posters, photographic prints, magazines etc. and convert them into digital images
for editing and display on computers.
• Any printed or handwritten document can be scanned and stored ina computer for
further processing.
• The user can scan important documents and store them permanently in the computer.
Hence no fear of loss of documents.

Audio-visual Input devices:


Audio Devices:
• Audio devices are used to either capture or create sound.
• They enable computers to accept music, speech or sound effects for recording or editing.
• Microphones and CD players are examples of audio input devices.
• Computers with microphone and speakers can be used to make telephone calls and do
video conferencing over the internet.

Video Devices:
• Video input devices are used to capture video from the outside world to the computer.
• Video means moving pictures along with sound. We have video cards to convert analog
video signals to digital data to store it in the computer.
• Digital cameras and web camera are examples of video input devices.

Advantages:
• Audio devices can be used by people who are visually impaired.
• Best used in situations where users want to avoid input through keyboard or mouse.
• Video input devices are very useful for applications such as video conferencing.
• Also used for security purposes.

Disadvantages:
• Audio input devices are not effective in noisy places.
• Difficult to distinguish between two similar sounding words.
• Videos and images captured, have a very big file size and hence needs to be compressed
before being stored in computer.

17
Introduction to C Programming BESCK204C
Introduction to C Programming
[2.2] OUTPUT DEVICES

Electromechanical devices that accept digital data from the computer and convert them
into human-understandable form.

Soft-copy devices
o Devices that produce electronic version of an output- file that is stored on hard disk, CD or pen
drive and is displayed on computer screen.
o Features of soft copy devices are:
✓ Output can be viewed only when computer is ON
✓ User can easily edit soft copy output.
✓ Searching is easy and fast.
✓ Distribution of soft copy is cheaper and can be done easily and quickly.
Monitor:
The monitor is an integral part of computer which displays both text and graphics. The
performance is measured in terms of image quality, resolution, energy consumption.

CRT (Cathode Ray Tube) Monitors:


The CRT monitors have a rarefied tube containing three electron guns.The guns emit electrons
create images. They usually have resolution of 640*840 pixels. They are large, heavy,energy efficient
and produces lot of heat.

18
Introduction to C Programming BESCK204C
Introduction to C Programming

Advantages:
• CRT monitors provides image of good quality.
• Are cheapest when compared to LCD and plasma monitors
• Images are clear even when you try to view from an angle.
Disadvantages:
• CRT monitors occupy large space on the desk
• They are bigger in size
• Power consumption is higher than the other monitors.

LCD (Liquid Crystal Display) Monitors:


The image is formed by applying voltage on crystals. The backlight is provided by
fluorescent light. They consume less power, generate less heat and have increased life span.

Advantages:
• LCD monitors are very compact and light weight.
• Consume less power
• They are more reliable on CRT
• They can be made in almost any size or shape
• They do not suffer from geometric distortion
Disadvantages:
• More expensive than CRT’s
• Images are not very clear when tried to view from an angle.

Projectors
➢ Is a device that takes image from a video source and projects it on to the screen or another surface.
➢ Allow users to change or adjust some features like brightness, sharpness and color settings.
➢ They are available in various shapes and sizes and are produced by many different companies.
➢ Projectors can be classifies into two categories:
o LCD projector: makes use of their own light to display the image on screen/wall.
▪ These are based on LCD technology.

19
Introduction to C Programming BESCK204C
Introduction to C Programming
▪ To use these, the room must be darkened else image will be blurred.
o Digital Light projector (DLP): uses number of mirrors to reflect the light.
Speakers
➢ Speakers were developed with different sizes and shapes and with different power and sound
quality.
➢ Computers have in-built speaker. Normal computer speakers are small in size.

Hard-copy Devices:
The devices that produce a physical form of output. The features include
✓ Editing and incorporating the edits in the hard copy is difficult.
✓ Hardcopy can be easily distributed to people who do not have computer.
✓ Searching for data in a hard copy is difficult job.

Printers:
Device that takes text and graphics information obtained from computer and prints it on paper.

Impact Printers:
It produces the hardcopy of output. The impact printers are old, noisy.But still dot-matrix printer
is in usage.

Dot-Matrix Printer: The print head of the dot-matrix printer has either 9 or 24 pins.
When the pins fire against the ribbon, an impression is created on the paper. The speed is 300
cps and doesn’t produce high quality output. It can produce multiple copies.

Daisy-wheel Printer: It employs a wheel with separate characters distributed along its
outer edge. The wheelscan be changed to obtain different set of fonts.

Line Printer: For heavy printing, the line printer is used. It uses a print chain containing
the characters. Hammers strike the paper to print and it rotates at the speed of 1200 lpm. It is also
noisy and is of low-quality.

Non-Impact Printers:
They are fast, quiet and of high resolution. The most commonly used non- impact
printers are laser and ink-jet printers. The thermal printer is not discussed here because it uses
heat toprint on high-sensitive paper.

Laser Printer: It works like a photocopier and uses toner i.e. black magnetic powder.
The image is created in the form of dots and passed from drums on to the paper. It has built-in
RAM which acts as buffer and RAMto store fonts. The resolution varies from 300 dpi to 1200
dpi and the speed is about 20 ppm.

Ink-jet Printer: These are affordable printers. It sprays tiny drops of ink at high pressure
as it moves along the paper. The separate cartridges are available for different colors. The

20
Introduction to C Programming BESCK204C
Introduction to C Programming
resolution is about 300 dpi, can print1 to 6 pages/min.

Plotters:
The plotter can make drawings. It uses one or more automated pens. The commands are taken
from special file called vector graphic files. Depending on type of plotter either paper or pen
moves. It can handle large paper sizes and it is used for creative drawings like buildings and
machines. They are slow and expensive.

21
Introduction to C Programming BESCK204C
Introduction to C Programming
CHAPTER-3
DESIGNING EFFICIENT PROGRAMS

[3.1] PROGRAMMING PARADIGMS

★ 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

Monolithic Programming

➔ Programs written using this type of language such as Assembly language and BASIC
consists of global data and sequential code.
➔ Global data can be accessed and modified from any part of the program.
➔ Sequential code is one in which all instructions are executed in specified sequence.
➔ Jump or ‘goto’ statements can be used.
Ex:

➔ Monolithic program have just one program module and does not support concept on
subroutines.
➔ Used only for very small and simple applications where reusability is not a concern.

22
Introduction to C Programming BESCK204C
Introduction to C Programming
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. Hence ‘goto’, ‘jump’ statements can be altered.
➔ FORTRAN AND COBOL are two procedural programming languages.

Advantages

○ The only goal is to write correct programs


○ Programs are easier to write as compared to monolithic programming

Disadvantages

○ No concept of reusability
○ Requires more time and effort to write programs
○ Programs are difficult to maintain
○ Global data is shared and therefore may get altered.

STRUCTURED PROGRAMMING

➔ Specifically designed to enforce a logical structure on the program to make it more


efficient and easier to understand and modify.
➔ Structured programming was basically defined to be used in large programs that require
large development team to develop different parts of the same program.
➔ 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 structure
➔ FIG:

23
Introduction to C Programming BESCK204C
Introduction to C Programming

➔ Structured programming is, therefore, based on modularization which groups related


statements together into modules.
➔ Modularization makes it easier to write, debug, and understand the program.
➔ For large and complex programs, the overall program structure may further require the
need to break the modules into pieces. This process continues until an individual piece of
code can be written easily.
➔ Almost every modern programming language similar to C, Pascal, etc., supports this
concept.
➔ Structured programming also supports selection and repetition as mentioned here.
➢ Selection allows for choosing any one of a numbered statements to execute, based
on the current status of the program.
➢ Selection statements contain keywords such as if', then', 'end if', or 'switch'

➢ In repetition, a selected statement remains active until the program reaches a point
where there is a need for some other action to take place.
➢ It includes keywords such as repeat', 'for', or 'do... until?

Advantages
● The goal of structured programming is to write correct programs that are easy to
understand and change.
● Modules enhance programmers productivity by allowing them to look at the big picture
first and focus on details later.
● 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.
● Each module performs a specific task.
● Each module has its own local data.

OBJECT-ORIENTED PROGRAMMING
➔ It is task-based and data-based and all relevant data and tasks are grouped together in
entities known as objects.
24
Introduction to C Programming BESCK204C
Introduction to C Programming

➔ Features of OOP
◆ Programs are data centered.
◆ Programs are divided in terms of objects and not procedures.
◆ 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.

[3.2] EXAMPLE OF STRUCTURED PROGRAM

Consider that an institute wants to create a program to manage the names and addresses of a list
of students.
For this we need to break down the program into following modules.
● Enter new names and addresses
● Modify existing entries.
● Sort entries.
● Print the list

Now each of these modules can be further broken down into smaller modules.
For example, first module can be subdivided into modules as follows.
● Prompt user to enter new data.
● Read the existing list from the disk.
● Add the name and address to the existing list.
● Save the updated list to the disk.

Similarly, “modify existing entries” can be further divided into modules such as follows.
● Read the existing list from disk.
● Modify one or more entries.
● Save the updated list to disk.
Observe that two submodules “read the list” and “save the updated list” are common to both
modules. Hence the structured programming language results ina layered program structure as shown
in figure.

25
Introduction to C Programming BESCK204C
Introduction to C Programming
[3.3] DESIGN AND IMPLEMENTATION OF EFFICIENT PROGRAMS

To design, develop, correct and efficient and maintainable programs, the programmer needs to
perform various activities during the development process.
The phases in the Software Development Life Cycle [SDLC] process is as shown in figure.

Requirement Analysis:
★ In this phase user’s expectations are gathered to know why the program/software has to be
built.
★ All gathered information or requirements are analyzed to arrive at the objective of overall
software product.
★ Lastly, documenting every identified requirement of the users in order to avoid doubts.
★ Functionality, capability, performance and availability of hardware and software components are
all analyzed in this phase.

Design:
★ Requirements document from previous phase acts as an input to the design phase.
★ Plan of actions is made before the actual development process can start and this plan will be
followed throughout the development process
★ The core structure of the software program is broken down into modules. The solution of the
program is then specified for each module in form of algorithms or flowcharts.

26
Introduction to C Programming BESCK204C
Introduction to C Programming

★ Design phase specifies how the program/software will be built.

Implementation:
★ Designed algorithms are converted into program code using any of the high level languages.
★ Choice of the language depends on type of the program such as whether it is system or application
oriented.
★ This phase is also called construction or code generation phase as code of the software is
generated in this phase.
★ While constructing, the development team checks whether software is compatible with available
hardware and software components that were mentioned in requirements documents created in
the first phase.

Testing:
★ In this phase, all modules are tested together to ensure overall system works well as a product.
★ Individual pieces of codes are already tested by the programmer but there are chances of having
bugs when integrated to form overall program structure.
★ In this phase, software is tested with large variety of inputs also known as test data, to ensure the
software is working as expected by users requirements.

Software deployment, training and support:


★ After code is tested and software or program is approved by the users, it is installed or deployed
in the production environment.
★ This phase is often ignored by the developers.
★ Maintenance and enhancements are ongoing activities that are done to cope with newly
discovered problems or new requirements.
★ If the cost of the maintenance phase exceeds then it indicates that the overall quality of one of
the phases is poor.
★ Hence it is better to rebuild software before maintenance cost shoots out of control.

[3.4] PROGRAM DESIGN TOOLS: ALGORITHMS, FLOWCHARTS, PSEUDOCODES

ALGORITHMS:

● The meaning of an algorithm is a formally defined procedure for performing some calculation.
● If a procedure is formally defined, then it must be implemented using some formal language, and
such languages are known as programming languages.
● The algorithm gives the logic of the program, that is, a step-by-step description of how to
arrive at a solution.
● It is considered to be an effective procedure for solving a problem in a finite number of steps.
● Algorithms are mainly used to achieve software reuse.
● 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.
27
Introduction to C Programming BESCK204C
Introduction to C Programming
● 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

Sequence:

★ Sequence means each step of the algorithm is executed in the specified order.
★ Ex: algorithm to add two numbers. This performs steps in sequential order.

Decision:

★ Decision statements are used when the outcome of the process depends on some
condition.
★ Ex: if x=y, then print “equal”. Hence the general form of if construct is

If condition then process

★ Conditions in this may evaluate either to a true value or false value.


★ Decision statement can also be stated in following manner called as if-else construct.

If condition

Then process1

Else process2

Repetition:
★ Involves executing one or more steps for a number of times, can be implemented using
constructs such as while, do-while and for loop
★ These loops execute one or more steps until some condition is true.

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.
● The symbols in the flowchart are linked together with arrows to show the flow of logic in the
process.

28
Introduction to C Programming BESCK204C
Introduction to C Programming
● The symbols used in a flowchart include the following

★ Start and end symbols are also known as the terminal symbols and are represented by
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 and is represented using a rectangle.
Activities include instructions such as add a to b, save the result.
★ Input/Output symbols are represented using 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 symbols coming out of it, one from
the bottom point and the other from the right point, correspond to Yes or True, and No or
False, respectively. The arrows should always be labeled. A decision symbol in a
flowchart can have more than two arrows, which indicates that a complex decision is
being taken.
★ Labeled connectors are represented by an identifying label inside a circle and are used
in complex or multi-sheet diagrams to substitute for arrows.

PSEUDOCODES

● Pseudocode is a compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language.
● It facilitates designers to focus on the logic of the algorithm without getting bogged down by the
details of language syntax.
● An ideal pseudocode must be complete, describing the entire logic of the algorithm, so that it can
be translated straightaway into a programming language.
● It is basically meant for human reading rather than machine reading, so it omits the details that
are not essential for humans. Such details include variable declarations, system-specific code, and
subroutines.

29
Introduction to C Programming BESCK204C
Introduction to C Programming

● Pseudocodes are an outline of a program that can easily be converted into programming
statements. They consist of short English phrases that explain specific tasks within a program's
algorithm. They should not include keywords in any specific computer language.
● The sole purpose of pseudocodes is to enhance human understandability of the solution.

[3.5] TYPES OF ERRORS

While writing programs, very often we get errors in our programs. 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

1. Runtime errors
2. Compile time errors
3. Linker errors
4. Logical errors

1. Runtime 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 than terminating it unexpectedly.

2. Compile Time Errors:


Compile-time errors occur at the time of compilation of the program. Such errors can be further
classified as follows:
Syntax Errors
Syntax errors are generated when rules of a programming language are violated.
Semantic Errors
Semantic errors are those errors which may comply with rules of the programming
language but are not meaningful to the compiler.

3. Linker Errors:

These errors occur when the linker is not able to find the function definition for a given
prototype.

4. Logical Errors:

➔ Logical errors are errors in the program code that result in unexpected and undesirable output
which is obviously not correct.

30
Introduction to C Programming BESCK204C
Introduction to C Programming

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

[3.6] 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, the following 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
behavior.

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 expand 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 modules is tested
individually using unit tests and then a system test is applied to test this entire system as one
system.
★ 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 tracing backward across the
entire source code until the real cause of error is detected.

Cause Elimination
★ In this approach, a list of all possible causes of error is developed.
★ Relevant tests are carried out to eliminate each of them
31
Introduction to C Programming BESCK204C
Introduction to C Programming
CHAPTER-4
INTRODUCTION TO C

[4.1] INTRODUCTION

➢ C is a general purpose, procedural, structured computer programming language developed


by Dennis Ritchie in the year 1972 at AT&T Bell Labs.
➢ C language was developed on UNIX and was invented to write UNIX system software.
➢ C is a successor of B language.
➢ There are different C standards: K&R C std, ANSI C, ISO C.

CHARACTERISTICS OF ‘C’ LANGUAGE


★ C is a high-level programming language, which enables programmers to concentrate on the
problem.
★ Small size- C has only 32 keywords. This makes it easy to learn as compared to other languages.
★ C makes extensive use of function calls.
★ C is a structured programming language.
★ Facilitates low level programming.
★ Supports pointers to refer to computer memory, arrays, structures and functions.
★ C is a portable language i.e. a program written on one computer can be written on another
computer with little or no modification.
★ C is an extensible language as it enables users to add his own functions to the C library.
★ C is more efficient which increases the speed of execution and management of memory
compared to low level languages.

USES OF ‘C’
★ C language is primarily used for system programming. Portability, efficiency, ability to access
specific hardware addresses make it a good choice for implementing OS applications.
★ C has been widely accepted by professionals that compilers, libraries and interpreters of other
programming languages are often written in C.
★ C is widely used to implement end-user applications.

[4.2] STRUCTURE OF C PROGRAM

C program is composed of preprocessor directive/commands, global declaration section and one


or more functions. (as shown in Fig)
Preprocessor directive
o Preprocessor Directives begins with a # symbol
o contain special instructions that indicate how to prepare the program for compilation.

32
Introduction to C Programming BESCK204C
Introduction to C Programming
o Commonly used preprocessor command is include which tells the compiler to execute the
program, some information is needed from the specified header file.

Global Declaration Section


o There will be some variable which has to be used in anywhere in program and used in
more than one function which will be declared as global.

main( ) function

o Every program must contain a main() function and is a part of every C program.
o the execution always starts from the main() function.
o All functions including main() are divided into two parts- the declaration section and
the statement section.
Declaration section precedes the statement section and is used to describe
data that will be used in the function.
Data declared within the function are known as local declaration as that data
will be visible only within that function. Ex: int a, b;
Statement section in a function contains the code that manipulates the data to
perform a specified task.
o All statements should end with a semicolon (;)
o Each function can have any number of statements arranged according to specific
meaningful sequence.

33
Introduction to C Programming BESCK204C
Introduction to C Programming
[4.3] WRITING THE FIRST C PROGRAM

#include <stdio.h>
int main()
{
printf(“\n Welcome to the world of C”);
return 0;
}
Output: Welcome to the world of C

#include<stdio.h>
is a preprocessor command that comes as the first statement in code. All preprocessor
commands start with (#) symbol.
This statement tells the compiler to include the standard input/output library or header file
in the program.
This header file contains functions for input and output of data such as reading values
from the keyboard and printing results on the screen.

int main()
int is the return value of the main function.
After all the statements in the program are written, the last statement in the
program returns an integer value to the operating system.

printf(“\n Welcome to the world of c”);


printf function is defined in stdio.h file and is sued to print text on the screen.
The message that has to be displayed on the screen is enclosed within double quotes and
put inside the brackets.

return 0;
this is a return command that is used to return a value 0 to the operating system to give an
indication that there were no errors during the execution of the program.

[4.4] FILES USED IN C PROGRAM


Every C program has 4 kinds of files associated with it

Source Code Files:


Contains source code of the program.
The file extension of any C source code file is ‘.c’ this file contains C code that define
main function or any other function.
main function is the starting point of execution when successfully compiled and run the
program.
C program may generally include even other source file.

34
Introduction to C Programming BESCK204C
Introduction to C Programming
Header Files:
Header files names end with ‘.h’ extension and names can only be letters, digits, dashes
and underscores.
Some advantages of header files are:
o Programmer wants to use the same subroutine in different programs.
o Programmer want to change or add subroutines and have those changes reflected
in all other programs.
Header file produces same results as copying the header file into each source file that
needs it.
Example of standard header file include
o string.h for string handling functions
o stdlib.h for some miscellaneous functions
o stdio.h for standardized input output functions
o math.h for mathematical functions
o alloc.h for dynamic memory allocation

Object Files

[4.5] COMPILING AND EXECUTING C PROGRAMS

➢ C is compiled language. Once program is written, it should run through a C compiler that can
create executable file to be run by the computer.
➢ The compiler translates the source code into object code. The object code contains machine
instructions for the CPU and calls to the OS API.
➢ Next step, the object file is processed with another special program called a linker.
➢ The output of the linker is an executable or runnable file.

35
Introduction to C Programming BESCK204C
Introduction to C Programming
➢ The compilation process is done in two steps:
o First step, the preprocessor program reads the source as text and produces another text file
as output.
o Source code line which begins with the # symbol is actually not written in C but in the
preprocessor language.
o The output of the preprocessor is a text file which does not contain any preprocessor
statements.
o The file is ready to be processed by the compiler.
o The linker combines the object file with library routines to produce final executable file.

o In second step, in the modular programming, the source code is divided in to two or more
source files.
o All these source files are compiled separately thereby producing multiple object files.
o These object files are combined by the linker to produce executable file.

36
Introduction to C Programming BESCK204C
Introduction to C Programming
[4.6] USING COMMENTS

o The purpose of the program code is not clear to the reader. Hence, it’s a good practice to place
some comments in the code to help reader understand the code.
o Comments are a way of explaining what a program does.
o the compiler ignores the comments during the formation of object file, hence these are non-
executable statements.
o C supports two types of comments
➢ // is used to comment a single line comment or line comment. This is placed
anywhere on the line and does not require to specifically end the file.
➢ /* is used to comment multiple statements and is ended with */ and all statements
that lie within these are commented. Also called as block comment.
Ex: /* C program to print hello world */
#include<stdio.h>
{
printf(“ hellow world…!!”);
// prints message
return 0; // returns a value 0 to operating system
}

o Since comments are not executed by the compiler, they do not affect the speed and size of the
compiled program.

[4.7] C TOKENS
➢ Tokens are the smallest or basic units of C program.
➢ One or more characters are grouped in sequence to form meaningful words. thesemeaningful
words are called as tokens.
➢ A token is collection of characters.
➢ There are 6 types of ‘C’ tokens:
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
vi. Special symbols

[4.8] CHARACTER SET IN C


Program: A program is a group of instructions given by the programmer to perform
aspecific task.
Character set of C language
➢ Definition: A symbol that is used while writing a program is called a character.
➢ A character can be:
37
Introduction to C Programming BESCK204C
Introduction to C Programming
o Alphabets/Letters (Lowercase a-z, Uppercase A-Z)
o Digits (0-9)
o Special Symbols ( ~ ‘ ! @ # % & * () - + / $ = \ { , } [ ] : ; “ “ ? etc)
o white space characters: these characters are used to print blank space on the screen
o escape sequences: \b, \n, \t, \t etc.

[4.9] KEYWORDS
✓ Keywords are also called as reserved words.
✓ They already have pre-defined meaning.
✓ Keywords should always be written in lowercase.
✓ The keywords meaning can’t be changed.
✓ Keywords cannot be used as identifiers.
✓ There are 32 keywords in ‘C’ program.

auto double if static


break else int struct
case enum long switch
char extern near typedef
const float register union
continue for return unsigned
default volatile short void
do goto signed while

Rules for keywords


1. Keywords should not be used as variables, function names, array names etc.
2. All keywords should be written in lowercase letters.
3. Keywords meaning cannot be changed by the users.

[4.10] IDENTIFIERS
Definition:
➢ Identifiers are the names given to program elements such as variables, constants, function
names, array names etc.
➢ It consists of one or more letters or digits or underscore.
Rules for identifiers
1. It must contain only alphabets (A to Z, a to z), numbers (0 to 9) and underscore ( _ ).
38
Introduction to C Programming BESCK204C
Introduction to C Programming
2. The First character should be an alphabet or an underscore _

Then First character is followed by any number of letters or digits.

3. It should not contain any special symbols apart from underscore.


4. There cannot be two successive underscores.
5. It should not have any space.
6. Keywords cannot be used as identifiers.
7. Identifiers are case sensitive.
8. Maximum length of an identifier is 31 characters.

Examples:
Valid Identifiers: integer, minimum, sum_total, row1

Invalid Identifiers: float - It is a keyword.


I am - It has space
123_Abc - It is starting with number

N1 + n2 - It contains special symbol (+)

[4.11] BASIC DATATYPES IN C

The data type defines the type of data stored in memory location or the typeof data the
variable can hold.

There are few basic data types supported in C


Integer data type (int):
➢ It stores an integer value or integer constant.
➢ An int is a keyword using which the programmer can inform the compiler that thedata
associated with this keyword should be treated as integer.
➢ C supports 3 different types of integers:
o short int,
o int,
o long int

39
Introduction to C Programming BESCK204C
Introduction to C Programming
n-bit Type size Range of unsigned Range of signed int
machine int be -2n to +2n -1
0 to 2n-1
16- bit short int 2 bytes 0 to 216-1 -215 to +215 -1
machine 0 to 65535 -32768 to +32767

int 2 bytes 0 to 216-1 -215 to +215 -1


0 to 65535 -32768 to +32767

long int 4 bytes 0 to 232-1 -231 to +231 -1


0 to 4294967295 -2147483648 to
+ 2147483647

Floating data type (float):


➢ A float is a keyword using which the programmer can inform the compiler that thedata
associated with this keyword should be treated as floating point number.
➢ The size is 4 bytes.
➢ The range is -3.4e38 to +3.4e38.
➢ Float can hold the real constant accuracy up to 6 digits after the decimal point.

Double data type (double):


o A double is a keyword using which the programmer can inform the compiler that the
data associated with this keyword should be treated as long floating point number.
o The size is 8 bytes.
o The range is from 1.7e-308 to 1.7 e+308.
o Double can hold real constant up to 16 digits after the decimal point.
Character data type (char):
➢ char is a keyword which is used to define single character or a sequence of character in c
language capable of holding one character from the local character set.
➢ The size of the character variable is 1 byte.
➢ The range is from -128 to +127.
➢ Each character stored in the memory is associated with a unique value termed asASCII
(American Standard Code for Information Interchange).
➢ It is used to represent character and strings.

40
Introduction to C Programming BESCK204C
Introduction to C Programming
[4.12] VARIABLES

➢ A variable is a name given to memory location where data can be stored.


➢ Using variable name data can be stored in a memory location and can be accessed or
manipulated very easily.
Rules for variables
• The First character should be an alphabet or an underscore _
• Then First character is followed by any number of letters or digits.
• No extra symbols are allowed other than letters ,digits and Underscore
• Keywords cannot be used as an identifier

Declaration of variables:

✓ Giving a name to memory location is called declaring a variable.


✓ Reserving the required memory space to store the data is called defining a variable.
✓ General Syntax:
datatype variable; (or)
datatype variable1, variable2,… ..... variable n;
example: int a;
float x, y;

double sum;

➢ From the examples we will come to know that “a” is a variable of type integer and allocates 2
bytes of memory. “x” and “y” are two variable of type float which will be allocated 4 bytes of
memory for each variable. “sum” is a double type variable which will be allocated with 8 bytes
of memory for each.
Variable Initialization
➢ Variables are not initialized when they are declared and defined, they contain garbage
values (meaningless values)
➢ The method of giving initial values for variables before they are processed is called
variable initialization.
➢ General Syntax:
var_name = expr;Where,

var_name is the name of the variable ,


expr is the value of the expression.
41
Introduction to C Programming BESCK204C
Introduction to C Programming
➢ The “expr” on the right- h a n d side is evaluated and stored in the variable
name(var_name) on left hand side.
➢ The expression on the right-hand side may be a constant, variable or a larger formula
built from simple expressions by arithmetic operators.
Examples:
int a=10; // assigns the value 10 to the integer variable a
[4.13] CONSTANTS

Constants are the values that does not changes during the execution of a program
OR Constants
refers to fixed values that do not change during the execution of a program.
The different types of constants are:
Integer constant
➢ Definition: An integer is whole number without any decimal point.no extra characters
are allowed other than + or _ .

➢ Three types of integers


• Decimal integers: are constants with a combination of digits 0 to 9,optional + or -
Ex: 123 , -345, 0 , 5436 , +79
• Octal integers: are constants with a combination of Digits from 0 to 7 but
it has a prefix of 0
Ex: 027 , 0657 , 0777645
• Hexadecimal integers: Digits from 0 to 9 and characters from a to f, it
must startwith 0X or 0x
Ex: 0X2 0x56 0X5fd 0xbdae

Real constants/Floating point:


➢ Floating point constants are base 10 numbers that are represented by fractional
parts, such as 10.5.They can be positive or negative.
➢ Two forms are:
i. Fractional form:
➢ A floating point number represented using fractional form has an integer part
followed by dot and a fractional part.
➢ Ex: 0.0083 215.5 -71. +0.56 etc..
ii. Exponential form:
➢ A floating point number represented using Exponent form has 3 parts
42
Introduction to C Programming BESCK204C
Introduction to C Programming
mantissa e exponent
➢ Mantissa is either real number expressed in decimal notation or integer.
➢ Exponent must be integer with optional + or –
➢ Ex 9.86 E 3 => 9.86*103
➢ Ex 9.86 E -3 => 9.86*10-3

Character constant
➢ A symbol enclosed within pair of single quotes is called character constant.
➢ Each character is associated with unique value called ASCII value.
➢ Ex: ‘9’, ‘$’
• Backslash constants (Escape sequence character)
➢ Definition: An escape sequence character begins with backslash and is followed
by one character.
➢ A backslash along with a character give rise to special print effects.
➢ It always start with backslash, hence they are called as backslash constants.

character name Meaning

\a Bell Beep sound

\b Backspace Cursor moves towards left by one


position
\n Newline Cursor moves to next line

\t Horizontal tab Cursor moves towards right by 8


position
\r Carriage return Cursor moves towards beginning of the
same line
\\ Backslash Backslash

String constant
➢ A sequence of characters enclosed within pair of double quotes is called string constant.
➢ The string always ends with a NULL character.
➢ Ex: “9” or “JCE”

43
Introduction to C Programming BESCK204C
Introduction to C Programming
Declaring Constant:
To declare a constant, const keyword is used and assign it a value.
For ex: const float pi =3.14
Specifies value of pi cannot be changed.
Another way to declare constant is by use of pre-processor command define
define is preceded with # symbol
Ex: #define pi 3.14159
Ex: #define service_tax 0.12

[4.14] INPUT/OUTPUT STATEMENTS IN C [Formatted input/output]


Displaying Output using printf
o printf is an output statement in C used to display the content on the screen.
o print: Print the data stored in the specified memory location or variable.
o Format: The data present in memory location is formatted in to appropriate data type.
o There are various forms of printf statements.
Method 1: printf(“ control string”);
o control string may be any character. The characters included within the double
quotes will be displayed on the output screen
o Example: printf(“Welcome to India”);
Output:
Welcome to India

Method 2:
printf(“ control string”, variable list);
o Control string also called as format string.
o Control string consist of format specifier of particular data type
o Format specifiers starts with % sign followed by conversion code.
o variable list are the variable names separated by comma.
Example:

int a=10;

float b=20;
printf(“ integer =%d, floating=%f”,a,b);
output:
integer=10, floating=20.00000

44
Introduction to C Programming BESCK204C
Introduction to C Programming

o Number of format specifiers must be equal to number of variables.


o While specifying the variables name make sure that it matches to the format
specifiers with in the double quotes.
Format Specifiers
➢ Format specifiers are the character string with % sign followed with a character.
➢ It specifies the type of data that is being processed.
➢ It is also called conversion specifier or conversion code

Symbols Meaning

%d Decimal signed integer number

%f float point number

%c Character

%o octal number

%x hexadecimal integer(Lower case letter x)

%X hexadecimal integer(Upper case letter X)

%e floating point value with exponent(Lower case letter e)

%E floating point value with exponent (Upper case letter E)

%ld long integer

%s String

%lf double

Input Function (scanf )

o Inputting Values Using scanf

o To enter the input through the input devices like keyboard we make use of scanf
statement.

General Syntax:
scanf(“control string”, list of address of variables);
Where:control string consists of the access specifiers/format specifiers.
o Format string consist of format specifier of particular data type
o Format specifiers starts with % sign followed by conversion code.

45
o List of addresses of variables consist of the variable name
preceded with &symbol(address operator).

Example: int a;
float b;
scanf(“%d%f”,&a,&b);
Rules for scanf

✓ No escape sequences or additional blank spaces should be specified in the format


specifiers.
✓ Ex: scanf(“%d %f”,&a,&b); //invalid
scanf(“%d\n%f”,&a,&b); //invalid
✓ & symbol is must to read the values, if not the entered value will not be stored in thevariable
specified. Ex: scanf(“%d%f”,a,b);//invalid

Note: Examples for input/output statements (refer examples done in the theory/lab)

You might also like