Besck204c Module-1
Besck204c Module-1
Introduction to C Programming
MODULE-1
CHAPTER-1
INTRODUCTION TO COMPUTERS
[1.1] COMPUTER
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.
➔ 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
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.
• 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.
❖ 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.
❖ 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.
❖ 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.
❖ Robotics
Robots are computer-controlled machines mainly used in the manufacturing process in
extreme conditions where humans cannot work.
❖ 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.
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
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.
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.
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.
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
★ 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
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
23
Introduction to C Programming BESCK204C
Introduction to C Programming
➢ 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.
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
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.
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.
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 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
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.
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.
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.
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
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.
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.
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.
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.
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
➢ 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.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.
[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 _
Examples:
Valid Identifiers: integer, minimum, sum_total, row1
The data type defines the type of data stored in memory location or the typeof data the
variable can hold.
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
40
Introduction to C Programming BESCK204C
Introduction to C Programming
[4.12] VARIABLES
Declaration of variables:
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,
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 _ .
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.
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
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
Symbols Meaning
%c Character
%o octal number
%s String
%lf double
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
Note: Examples for input/output statements (refer examples done in the theory/lab)