KEMBAR78
Bpops103 Module 1 | PDF | Personal Computers | Computer Data Storage
0% found this document useful (0 votes)
21 views48 pages

Bpops103 Module 1

Chapter 1 introduces computers as electronic devices that process data and produce information, highlighting their key characteristics such as speed, accuracy, automation, and versatility. It discusses the stored program concept, the evolution of computers from early mechanical devices to modern digital systems, and outlines the historical timeline of significant developments in computing technology. The chapter also categorizes computers into five generations based on technological advancements, detailing their hardware, memory, and software characteristics.

Uploaded by

prathamesh427869
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)
21 views48 pages

Bpops103 Module 1

Chapter 1 introduces computers as electronic devices that process data and produce information, highlighting their key characteristics such as speed, accuracy, automation, and versatility. It discusses the stored program concept, the evolution of computers from early mechanical devices to modern digital systems, and outlines the historical timeline of significant developments in computing technology. The chapter also categorizes computers into five generations based on technological advancements, detailing their hardware, memory, and software characteristics.

Uploaded by

prathamesh427869
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/ 48

Principles of Programming using C BPOPS103 Module 1-Chapter-1

CHAPTER 1
INTRODUCTION TO COMPUTERS

1. Introduction
A computer, in simple terms, can be defined as an electronic device that is designed to accept data,
perform the required mathematical and logical operations at high speed, and output the result.
Data: Raw facts/ figures

Information: Processed data


Program: set of instructions known as a Program

. 1.2 Characteristics of Computers


The important characteristics of a computer (refer to Figure 1.1) are discussed in the
following text.

Speed: Computers can perform millions of operations per second. The speed of computers is usually
given in nanoseconds and picoseconds, where 1 nanosecond =1 × 10−9 seconds and 1 picoseconds =
1 × 10−12 seconds.
Accuracy: A computer gives accurate results, provided the correct data and set of instructions are input
to it. Hence, in the event of an error, it is the user who has fed the incorrect data/program is responsible.
This clearly means that the output generated by a computer depends on the given instructions and input
data. If the input data is wrong, then the output will also be erroneous.
Automation: Besides being very fast and accurate, 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.
Diligence: Computers never get tired of a repetitive task. It can continually 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.
Versatile: Today, computers are used in our daily life in different fields. For example, they are used as
personal computers (PCs) for home use, for business-oriented tasks, weather forecasting, space
exploration, teaching, railways, banking, medicine, and so on, indicating that computers can perform
different tasks simultaneously. Therefore, computers are versatile devices as they can perform multiple
tasks of different nature at the same time.
Memory: Computers also have internal or primary memory (Random Access Memory) as well as

1
Principles of Programming using C BPOPS103 Module 1-Chapter-1

external or secondary memory. While the internal memory of computers is very expensive and limited in
size, the secondary storage is cheaper and of bigger capacity.

The computer stores a large amount of data and programs in the secondary storage space. The stored
data and programs can be retrieved and used whenever required. Secondary memory is the key for data
storage. Some examples of primary memory devices include RAM and ROM and secondary devicesinclude
floppy disks, optical disks (CDs and DVDs), hard disk drives (HDDs), and pen drives.

No IQ: Although the trend today is to make computers intelligent by inducing artificial intelligence (AI)
in them, they still do not have any decision-making abilities of their own. They need guidance to perform
various tasks.

Economical: Using computers also reduces manpower requirements and leads to an elegant and efficient way
of performing various tasks. Hence, computers save time, energy, and money. When compared to other
systems, computers can do more work in lesser time.

1.3 Stored Program Concept


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

1.3.1 Types of Stored Program Computers


A computer with a Von Neumann architecture stores data and instructions in the same memory. There is a serial
machine in which data and instructions are selected one at a time.

Data and instructions are transferred to and from memory through a shared data bus. Since there is a single bus
to carry data and instructions, process execution becomes slower.

Later Harvard University proposed a stored program concept in which there was a separate memory to store data
and instructions. Instructions are selected serially from the instruction memory and executed in the processor.
When an instruction needs data, it is selected from the data memory. Since there are separate memories,
execution becomes faster.

2
Principles of Programming using C BPOPS103 Module 1-Chapter-1

1.4 History of Computers


Early computers were designed not for entertainment but for solving number-crunching problems. These
computers were punch-card based computers that took up entire rooms. Today, our smart phones have
much more computing power than that was available in those early computers.
Timeline of Developments
300 BC: The abacus was an early aid for mathematical computations and was designed to aid human’s
memory while performing calculations. A skilled abacus operator can add and subtract with the same
speed as that of a person performing the same calculation using a hand calculator. The invention of abacus
is often wrongly attributed to China. It was used by the Babylonians even in 300 BC andis still in use
today (in the Far East).
1822: English mathematician Charles Babbage designed a steam-driven calculating machine that could
compute tables of numbers. Though the project failed as he could not complete the construction of the
engine, it laid the foundation for the first computer.
1890: Herman Hollerith, an American inventor, designed a punched card system to calculate the 1880
census. The system completed the task in three years saving the US government $5 million. Later Herman
established a company that we today know as IBM.
1936: British mathematician Alan Turing introduced a universal machine called the Turing machine
capable of computing anything that is computable. The central concept of the modern computer is based
on this machine.
1941: John Vincent Atanasoff, a Bulgarian-American physicist, and his graduate student, Clifford Berry,
at Iowa State College designed Atanasoff–Berry computer (ABC) that could solve 29 equations
simultaneously. It was the first time a computer could store information in its main memory.
1943–1944: John W. Mauchly and J. Presper Eckert built the Electronic Numerical Integrator and
Calculator (ENIAC), which is considered as the grandfather of digital computers. It filled a 20 × 40 feet
room and had 18,000 vacuum tubes.
1946: Mauchly and Presper designed the UNIVAC, which was the first commercial computer for
business and government applications.
1947: William Shockley, John Bardeen, and Walter Brattain of Bell Laboratories invented the transistor.
Soon vacuum tubes in computers were replaced by transistors.
1953: Grace Hopper developed the first computer language COBOL.
1954: The FORTRAN programming language was developed.
1958: Jack Kilby of Texas Instruments and Robert Noyce at Fairchild Semiconductor Corporation
separately invented integrated circuit, which is commonly known as the computer chip.
1964: Douglas Engelbart developed a prototype of the modern computer, with a mouse and a graphical
user interface (GUI). This was a remarkable achievement as it shifted computers from a specialized
machine for scientists and mathematicians to general public.
1969: Unix operating system was developed at Bell Labs. It was written in the C programming language
and was designed to be portable across multiple platforms. Soon it became the operating system of choice
among mainframes at large companies and government entities.
1970: DRAM chip was introduced by Intel.
1971: Alan Shugart with his team in IBM invented the floppy disk which allowed data to be shared
among computers.
1973: Robert Metcalfe, a research member at Xerox, developed Ethernet for connecting multiple
computers and other hardware.
1974–1977: Personal computers started becoming popular.

3
Principles of Programming using C BPOPS103 Module 1-Chapter-1

1975: Paul Allen and Bill Gates started writing software for the Altair 8800 using the new BASIC
language. On April 4, they both formed their own software company, Microsoft.
1976: Steve Jobs and Steve Wozniak started Apple Computers and developed Apple I, the first
computer with a single-circuit board.
1977: Apple II was launched that offered colour graphics and incorporated an audio cassette drive for
storage.
1978: WordStar, a word processor application, was released by MicroPro International.
1979: VisiCalc, the first computerized spreadsheet program for personal computers, was unveiled.
1981: The first IBM personal computer was introduced that used Microsoft’s MS-DOS operating
system. The term PC was popularized.
1983: The first laptop was introduced. Moreover, Apple introduced Lisa as the first personal computer
with a GUI with drop-down menus and icons.
1985: Microsoft announced Windows as a new operating system.
1986: Compaq introduced Deskpro 386 in the market, which was a 32-bit architecture machine that
provides speed comparable to mainframes.
1990: Tim Berners-Lee invented World Wide Web with HTML as its publishing language.
1993: The Pentium microprocessor introduced the use of graphics and music on PCs.
1994: PC games became popular.
1996: Sergey Brin and Larry Page developed the Google search engine at Stanford University.
1999: The term Wi-Fi was introduced when users started connecting to the Internet without wires.
2001: Apple introduced Mac OS X operating system, which had protected memory architecture and
preemptive multi tasking, among other benefits. To stay competitive, Microsoft launched Windows XP.
2003: The first 64-bit processor, AMD’s Athlon 64, was brought into the consumer market.
2004: Mozilla released Firefox 1.0 and in the same year Facebook, a social networking site, was
launched.
2005: YouTube, a video sharing service, was launched. In the same year, Google acquired Android,
aLinux-based mobile phone operating system.
2006: Apple introduced MacBook Pro, its first Intel-based, dual-core mobile computer.
2007: Apple released iPhone, which brought many computer functions in the smartphone.
2009: Microsoft launched Windows 7 in which users could pin applications to the taskbar.
2010: Apple launched iPad, which revived the tablet computer segment.
2011: Google introduced Chromebook, a laptop that runs on the Google Chrome operating system.
2015: Apple released the Apple Watch. In the same year, Microsoft launched Windows 10.

4
Principles of Programming using C BPOPS103 Module 1-Chapter-1

Generation of Computers
➢ First Generation (1940–1956)
➢ Second Generation (1956–1963)
➢ Third Generation (1964–1971)
➢ Fourth Generation (1971–1989)
➢ Fifth Generation (1989–Present)

First Generation (1940–1956)


Hardware Technology First generation computers were manufactured using thousands of vacuum
tubes (see Figure 1.3); a vacuum tube is a device made of fragile glass.
Memory Electromagnetic relay was used as primary memory and punched cards were used to store
data and instructions.
Software Technology Programming was done in machine or assembly language.
Used for Scientific applications
Examples ENIAC, EDVAC, EDSAC, UNIVAC I, IBM 701
Highlights
• They were the fastest calculating device of those times
• Computers were too bulky and required a complete room for storage
• Highly unreliable as vacuum tubes emitted a large amount of heat and burnt frequently
• Required air-conditioned rooms for installation
• Costly
• Difficult to use
• Required constant maintenance because vacuum tubes used filaments that had limited life time. Therefore,
these computers were prone to frequent hardware failures.

Figure 1.3 Vacuum tube

Second Generation (1956–1963)


Hardware Technology Second generation computers were manufactured using transistors (see Figure
1.4). Transistors were reliable, powerful, cheaper, smaller, and cooler than vacuum tubes.
Memory Magnetic core memory was used as primary memory; magnetic tapes and magnetic disks
were used to store data and instructions. These computers had faster and larger memory than the first
generation computers.
Software Technology Programming was done in high level programming languages. Batch operating
system was used.
Used for Scientific and commercial applications
Examples Honeywell 400, IBM 7030, CDC 1604, UNIVAC LARC
Highlights
• Faster, smaller, cheaper, reliable, and easier to use than the first generation computers
• They consumed 1/10th the power consumed by first generation computers
• Bulky in size and required a complete room for its installation

5
Principles of Programming using C BPOPS103 Module 1-Chapter-1

• Dissipated less heat than first generation computers butstill required air-conditioned rooms
• Costly
• Difficult to use
• Faster, smaller, cheaper, reliable, and easier to use thanthe first generation computers

Figure 1.4 Transistors

Third Generation (1964–1971)


Hardware Technology Third generation computers were manufactured using integrated chips (ICs)
(shown in Figure 1.5). ICs consist of several components such as transistors, capacitors, and resistors
on a single chip to avoid wired interconnections between components. These computers used SSI and
MSI technology. Minicomputers came into existence.
Memory Larger magnetic core memory was used as primary memory; larger capacity magnetic tapes
and magnetic disks were used to store data and instructions.
Software Technology Programming was done in high level programming languages such as
FORTRAN, COBOL, Pascal, and BASIC. Time sharing operating system was used. Software was
separated from the hardware. This allowed users to invest only in the software they need.
Used for Scientific, commercial, and interactive online applications
Examples IBM 360/370, PDP-8, PADP-11, CDC6600
Highlights
• Faster, smaller, cheaper, reliable, and easier to use than the second generation computers
• They consumed less power than second generation computers
• Bulky in size and required a complete room for installation
• Dissipated less heat than second generation computers but still required air-conditioned rooms
• Costly
• Easier to use and upgrade

Fourth Generation (1971–1989)


Hardware Technology Fourth generation computers were manufactured using ICs with LSI (Large
Scale Integrated) and later with VLSI technology (Very Large Scale Integration). Microcomputers
came into existence. Use of personal computers became widespread. High speed computer networks
in the form of LANs, WANs, and MANs started growing. Besides mainframes, supercomputers were
also used.
Memory Semiconductor memory was used as primary memory, large capacity magnetic disks were
used as built- in secondary memory. Magnetic tapes and floppy disks were used as portable storage
devices.
Software Technology Programming was done in high level programming language such as C

6
Principles of Programming using C BPOPS103 Module 1-Chapter-1

and C++. Graphical User Interface (GUI) based operating system (e.g. Windows) was introduced. It
had icons and menus among other features to allow computers to be used as a general purpose machine
by all users. UNIX was also introduced as an open source operating system. Apple Mac OS and MS
DOS were also released during this period. All these operating systems had multi-processingand multi-
programming capabilities.
Used for Scientific, commercial, interactive online, and network applications
Examples IBM PC, Apple II, TRS-80, VAX 9000, CRAY-1, CRAY-2, CRAY-X/MP
Highlights Faster, smaller, cheaper, powerful, reliable,and easier to use than the previous generation
computers

Figure 1.6 VLSI chip

Fifth Generation (1989–Present)


Hardware Technology Fifth generation computers are manufactured using ICs with ULSI (Ultra Large
Scale Integrated) technology. The use of Internet became widespread and very powerful mainframes,
desktops, portable laptops, and smartphones are being used commonly. Supercomputers use parallel
processing techniques.

Memory Semiconductor memory is used as primary memory; large capacity magnetic disks are used
as built-in secondary memory. Magnetic tapes and floppy disks were used as portable storage devices,
which have now been replaced by optical disks and USB flash drives.
Software Technology Programming is done in high-level programming languages such as Java,
Python, and C#. Graphical User Interface (GUI)-based operating systems such as Windows, Unix,
Linux, Ubuntu, and Apple Mac are being used. These operating systems are more powerful and user
friendly than the ones available in the previous generations.
Used for Scientific, commercial, interactive online, multimedia (graphics, audio, video), and network
applications
Examples IBM notebooks, Pentium PCs, SUM workstations, IBM SP/2, Param supercomputer
Highlights
• Faster, smaller, cheaper, powerful, reliable, and easier to use than the previous generation computers
• Speed of microprocessors and the size of memory are growing rapidly
• High-end features available on mainframe computers in the fourth generation are now available on the
microprocessors
• They consume less power than computers of prior generations
• Air-conditioned rooms required for mainframes and supercomputers but not for microprocessors

7
Principles of Programming using C BPOPS103 Module 1-Chapter-1

1.5 Classifications of Computers


Computers can be broadly classified into four categories based on their speed, amount of data that
they can process, and price.
▪ Supercomputers
▪ Mainframe computers
▪ Minicomputers
▪ Microcomputers

Supercomputers:
▪ The supercomputer is the fastest, most powerful, and most expensive computer.
▪ Supercomputers were first developed in the 1980s to process large amounts of data and to
solve complex scientific problems.
▪ Supercomputers use parallel processing technology and can perform more than one trillion
calculations in a second.
▪ A single supercomputer can support thousands of users at the same time. Such computers are
mainly used for weather forecasting, nuclear energy research, aircraft design, automotive
design, online banking, controlling industrial units, etc.
▪ Some examples of supercomputers are CRAY-1, CRAY-2, Control Data CYBER
205, and ETA A-10.

Mainframe Computers:
▪ Mainframe computers are large-scale computers.
▪ These are very expensive.
▪ 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 Terminals
➢ Intelligent Terminals
Dumb Terminals: Dumb terminals consist of only a monitor and a keyboard (or mouse). They do
not have their own CPU and memory and use the mainframe system’s CPU and storage devices.

Intelligent Terminals: intelligent terminals have their own processor and thus can perform some
processing operations. 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 of users frequently access the data stored in their databases.

Minicomputers:
As the name suggests, minicomputers are smaller, cheaper, and slower than mainframes. They
are called minicomputers because they were the smallest computer of their times. Also known as
midrange computers, the capabilities of minicomputers fall between mainframe and personal
computers.
Minicomputers are widely used in business, education, hospitals, government organizations, etc.
While some minicomputers can be used only by a single user, others are specifically

8
Principles of Programming using C BPOPS103 Module 1-Chapter-1

designed to handle multiple users simultaneously. Usually, single-user minicomputers are used
for performing complex design tasks. As with mainframes, minicomputers can also be used as
servers in a networked environment, and hundreds of PCs can be connected to it.

The first minicomputer was introduced by Digital Equipment Corporation (DEC) in the mid-
1960s. Other manufacturers of minicomputers include IBM Corporation (AS/400 computers),
Data General Corporation, and Prime Computer.

Microcomputers:
Microcomputers, commonly known as PCs, are very small and cheap. The first microcomputer was
designed by IBMin 1981 and was named IBM-PC. Later on, many computer hardware companies
copied this design and termed their microcomputers as PC-compatible, which refers to any PC that
is based on the original IBM PC design.

Another type of popular PC is designed by Apple. PCs designed by IBM and other PC-
compatible computers have a different architecture from that of Apple computers. Moreover, PCs
and PC-compatible computers commonly use the Windows operating system, while Apple
computers use the Macintosh operating system (MacOS). PCs can be classified into the following
categories:
Desktop PCs
A desktop PC is the most popular model of PCs. The system unit of the desktop PC can be placed
flat on a desk or table. It is widely used in homes and offices.
Laptops
Laptops (Figure 1.9) are small microcomputers that can easily fit inside a briefcase. They are very
handy and can easily be carried from one place to another. They may also be placed on the user’s lap
(thus the name). Hence, laptops are very useful, especially when going on long journeys. Laptops
operate on a battery and do not always have to be plugged in like desktop computers.
The memory and storage capacity of a laptop is almost equivalent to that of a desktop computer.
As with desktop computers, laptops also have hard disk drives, USB drives, etc. For input,laptops
have a built-in keyboard and a trackball/touchpad, which is used as a pointing device (as a mouse is
used for a desktop PC).
Today, laptops have the same features and processing speed as the most powerful PCs. However,

Figure 1.9 Laptop


a drawback is that laptops are generally more expensive than desktop computers. These computers
are very popular among business travelers.
Workstations
Workstations are single-user computers that have the same features as PCs, but their processing
speed matches that of a minicomputer or mainframe computer. Workstation computers have
advanced processors, more RAM and storage capacity than PCs. Therefore, they are more expensive
and powerful than a normal desktop computer.
Although workstation computers are widely used as powerful single-user computers by scientists, engineers, architects,
and graphic designers, they can also be used as servers in a networked environment.

9
Principles of Programming using C BPOPS103 Module 1-Chapter-1

Network Computers
Network computers have less processing power, memory, and storage than a desktop computer.
These are specially designed to be used as terminals in a networked environment. For example,
some network computers are specifically designed to access data stored on a network (including the
Internet and intranet).

Network computers that are specifically designed to access only the Internet or intranet are often known
as Internet PCs or Internet boxes. Some network computers used in homes do not even have a monitor.
Such computers may be connected to a television, which serves as the output device. The most
common example of a home-based network computer is Web TV, which enables the user to connect a
television to the Internet. The Web TV is equipped with a special set-top box that is used to connect
tothe Internet.

Handheld Computers
The mid-1990s witnessed a range of small personal computing devices that are commonly known
as handheld computers, or mobile computers. These computers are called handheld computers
because they can fit in one hand, while users can use the other hand to operate them. Handheld
computers are very small in size, and hence they have small-sized screens and keyboards. These
computers are preferred by business travelers and mobile employees whose jobs require them to
move from place to place.
Some examples of handheld computers are as follows:
➢ Smartphones
➢ Tablet PCs
Smartphones These days, cellular phones are web-enabled telephones. Such phones are also known as
smartphones because, in addition to basic phone capabilities, they also facilitate the users to access the Internet
and send e-mails, edit Word documents, generate an Excel sheet, create a presentation, and lots more.

Tablet PCs A tablet PC (see Figure 1.10) is a computing device that is smaller than a laptop,but bigger than a
smartphone. Features such as user-friendly interface, portability, and touch screen have made them very popular
in the last few years. These days, a wide range of high-performance tablets are available in the market. While all
of them look similar from outside, they may differ in features such as operating system, speed of data
connectivity, camera specifications, size of the screen, processing power, battery life, and storage capability.

Uses The following are the uses of Tablet PCs:


▪ View presentations
▪ Videoconferencing
▪ Reading e-books, e-newspaper

▪ Watching movies
▪ Playing games
▪ Sharing pictures, video, songs, documents, etc.
▪ Browsing the Internet
▪ Keeping in touch with friends and family on popular social networks, sending emails
▪ Business people use them to perform tasks such as editing a document,
exchanging documents, taking notes, and giving presentations
▪ Tablets are best used in crowded places such as airports and coffee shops,
where size and portability become more important.

10
Principles of Programming using C BPOPS103 Module 1-Chapter-1

Figure 1.10 Tablet

1.6 Applications of Computers

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 networks that connects computers all over the world. It gives the user
access to an enormous amount of information, much more than available in any library. Using e-mail, the user
can communicate in seconds with a person who is located thousands of miles away. Chat software enables
users to chat with another person in real-time (irrespective of the physical location of that person). 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-Dmodels and special effects in science fiction
and action movies.

Desktop publishing Desktop publishing software enables us to create page layouts for entire books.
After discussing how computers are used in today’s scenario, let us now have a look at the different areas where
computers are being widely utilized.

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.

e-commerce used to perform transactions between business partners or customers has several applications such
as home banking, electronic shopping, buying stocks, finding a job, conducting an auction, marketing and
advertising products or services, and providing customer service. The following are techniques in which e-
commerce helps users to conduct business transactions.

Business-to-consumer or B2C: In this form of electronic commerce, business companies deploy their websites
on the Internet to sell their products and services to the customers. On their websites, they provide features such
as catalogues, interactive order processing system, secure electronic payment system, and online customer
support.

Business-to-business or B2B: This type of electronic commerce involves business transactions performed
between business partners (customers are not involved). For example, companies use computers and networks
(in the form of extranets) to order raw materials from their suppliers. Companies can also use extranets to supply
their products to their dealers.

11
Principles of Programming using C BPOPS103 Module 1-Chapter-1

Consumer-to-consumer or C2C: This type of electronic commerce enables customers to carry business
transactions among themselves. For example, on auction websites, a customer sells his/her product which is
purchased by another customer.

Electronic banking: Electronic banking, also known as cyber banking or online banking, supports various banking
activities conducted from home, a business, or on the road instead of a physical bank location.

Bioinformatics
Bioinformatics is the application of computer technology to manage large amount of biological information.
Computers are used to collect, store, analyze, and integrate biological and genetic information to facilitate gene-
based drug discovery and development. The need for analysis has become even more important with enormous
amount of genomic information available publicly fromthe Human Genome Project.
Health care
Last few years have seen a massive growth of computers and smartphone users. Like in our daily lives, computers
have also become a necessary device in the health care industry. The following are areas in which computers are
extensively used in the health care industry.
Storing records: To begin with, computers are first and foremost used to store the medical records of patients.
Earlier, patient records were kept on paper, with separate records dealing with different medical issues from
separate healthcare organizations. With time, the number of prescriptions, medical reports, etc., grow in volume
making it difficult to maintain and analyze. Use of computers to store patient records has been a game-changer in
terms of improving the efficiency and accuracy of the entire process.

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.
Computers also help to determine the cause of an affliction or illness. For example, computers can combine
ultrasonography and imaging in fields like cardiology to check the functionality of the heart. In case of a serious
ailment, the causes can be detected in less time and treatment can be started at the earliest thereby saving a
number of lives.

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. Doctors sitting in hospitals can monitor their patients sitting in their homes by using
computer-based systems. As soon as warning signs of serious illnesses are spotted, they alert the concerned
doctor quickly.

Geographic Information System and Remote Sensing


A geographic information system (GIS) is a computer- based tool for mapping and analyzing earth’s features.
It integrates database operations and statistical analysis to be used with maps. GIS manages location- based
information and provides tools for display and analysis of statistics such as population count, types of vegetation,
and economic development opportunities. Such typeof 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 analyzed to derive useful information.

13
Principles of Programming using C BPOPS103 Module 1-Chapter-1

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. Meteorology has applications in many diverse fields such as the military, energy production,
transport, agriculture, and construction.

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. Weather forecasting is done by collecting
quantitative data about the current state of the atmosphere and analyzing the atmospheric processes to project
how the atmosphere will evolve.
Aviation meteorology: Aviation meteorology studies the impact of weather on air traffic management. It helps
cabin crews to understand the implications of weather on their flight plan as well as their aircraft.
Agricultural meteorology: Agricultural meteorology deals with the study of effects of weather and climate on
plant distribution, crop yield, water-use efficiency, plant and animal development.
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.

Using animation software, we can reproduce real- world phenomena such as fire, smoke, fluids, movement of
chemicals through the air and ground, and the respiratory system to name a few. Animation is an easy and
effective way to show complex interactions or events. Thus, it is an excellent tool for educating an audience.
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.
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 analyzing
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 asafe landing.
They are also used to research about hotels in an area, reserve rooms, or to rent a car.

14
Principles of Programming using C BPOPS103 Module 1-Chapter-1

Simulation
Supercomputers that can process enormous amount of data are widely used in simulation tests. Simulation of
automobile crashes or airplane emergency landings is done to identify potential weaknesses in designs without
risking human lives. Supercomputers also enable engineers to design aircraft models and simulate the effects that
winds and other environmental forces have on those designs. Astronauts are trained using computer-simulated
problems that could be encountered during launch, in space, or upon return to 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. The
remote stations on the earth compare all these quantities with the desired values, and in case these values need to
be modified to enhance the performance of the spacecraft, signals are immediately sent that set in motion the
mechanics to rectify the situation.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. Moreover, teachers at all levels can use computers to administer
assignments and keep track of grades. Students can also give exams online and get instant results.
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).
Computerized process control (with or without human intervention) is used to enhance efficiency in applications
such as production of various chemical products, oil refining, paper manufacture, and rolling and cutting steel to
customer requirements.
Robotics
Robots are computer-controlled machines mainly used in the manufacturing process in extreme conditions where
humans cannot work. For example, in high temperature, high pressure conditions or in processes that demand
very high levels of accuracy. The main distinguishing feature between a robot and other automated machines is
that a robot can be programmed to carry out a complex task and then reprogrammed to carry out another complex
tasks.
Decision Support Systems
Computers help managers to analyze 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 analyze 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.

15
Principles of Programming using C BPOPS103 Module 1-Chapter-1

1.7 Basic Organization of a Computer


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

Refer to Figure 1.11, which shows the interaction between the different units of a 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 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 main memory, is the storage area that is directly
accessible by the CPU at very high speeds. It is used to store the data and parts of programs, the
intermediate results of processing, and the recently generated results of jobs that are currently being
worked on by the computer. Primary storage space is very expensive and therefore limited in capacity.
Another drawback of main memory is that it 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 of 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 Cand 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 printer. 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.

17
Principles of Programming with C BPOPS103 Module 1

Control: The control unit (CU) is the central nervous system of the entire computer system. It manages
and controls all the components of the computer system. It is the CU that decides the manner in which
instructions will be executed and operations performed. It takes care of the step-by-step processing of
all operations that are performed in the computer.
Note that the CPU is a combination of the Arithmetic Logic Unit (ALU) and the Control Unit (CU).
The CPU is better known as the brain of the computer system because the entire processing of data is
done in the ALU, and the CU activates and monitors the operations of other units (such as input, output,
and storage) of the computer system.
Processing: The process of performing operations on the data as per the instructions specified by the
user (program) is called processing. Data and instructions are taken from the primary memory and
transferred to the ALU, which performs all sorts of calculations. 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 may move from main memory
to the ALU multiple times before the processing is over.

18
Module-1
Principles of Programming using C BPOPS103

CHAPTER 2
INPUT AND OUTPUT DEVICES

2.1 Input Devices


An input device is used to feed data and instructions into the computer. Figure 2.1 categorizes input
devices into different groups.

Fig 2.1 Categories of Input Devices

2.1.1 Keyboard
The keyboard is the main input device for computers. Computer keyboards look very similar to the
keyboards of typewriters. The standard keyboard consists of 101 keys. They are as follows.

Alphabet Keys-Print letters of alphabet-26


Numeric Keys-To print numbers-10
Functional Keys- Used by Applications-12
Control Keys-Used to handle the control of the Cursor and the screen-2
Arrow Keys-Move the cursor on the screen also called (Navigational Keys)-4
Home-End Keys: Used to move the cursor to the beginning and end of the current line respectively-2
Page Up-Page Down: Move the cursor to the up and down-2
Insert-1, Delete-1, Capslock-1, Esc-1, Backspace-1, Spacebar-1, Special symbols-13,
Shift keys-2, Window start keys-2, Control Keys-2 etc
.
2.1.2 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 commands menu, to draw graphs, etc. Some examples of pointing
devices include Mouse, Trackball, Light Pen, Joystick, and Touchpad.
Module-1
Principles of Programming using C BPOPS103

2.1.3 Handheld Devices


A handheld device is a pocket-sized computing device with a display screen and touch input and/or a
miniature keyboard. Some common examples of handheld devices include smartphones, PDAs, handheld
game consoles, and portable media players (such as iPod).

2.1.4 Optical Devices


Optical devices, also known as data-scanning devices, use light as a source of input for detecting or
recognizing different objects such as characters, marks, codes, and images. The optical device converts these
objects into digital data and sends it to the computer for further processing. Some optical devices include
barcode readers, image scanners, Optical Character Recognition (OCR) devices, Optical Mark Readers
(OMR), and Magnetic Ink Character Recognition (MICR) devices.

2.1.5 Audio-visual Input Devices


Today, all computers are multimedia-enabled, that is, computers not only allow one to read or write text, but
also enable the user to record songs, view animated movies, etc. Hence, in addition to having a keyboard
and a mouse, audio– video devices have become a necessity today.

2.2 Output Devices

Fig 2.2 Output Devices

Soft copy devices: These devices produce an electronic version of an output


For example, a file that is stored on a hard disk, CD, or pen drive and is displayed on the computer
screen.

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

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.
Module-1
Principles of Programming using C BPOPS103

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.

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.

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. Thewheel
scan 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 to print 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 RAM to 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 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.
Module-1
Principles of Programming using C BPOPS103

CHAPTER 3
Designing Efficient Programs
3.1 Programming Paradigms
It 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 depend.

3.1.1 Monolithic Programming

3.1.2 Procedural Programming


Module-1
Principles of Programming using C BPOPS103

3.1.3 Structured Programming


Module-1
Principles of Programming using C BPOPS103

3.1.4 Object-oriented Programming (OOP)


Module-1
Principles of Programming using C BPOPS103

3.2 Example of a Structured Program

3.3 Design and Implementation of Efficient Programs


The design and development of correct, efficient, and maintainable programs depends on the approach
adopted by the programmer to perform various activities that need to be performed during the development
process. The entire program or software (collection of programs) development process is divided into a
number of phases where each phase performs a well-defined task. Moreover, the output of one phase provides
the input for its subsequent phase.
Module-1
Principles of Programming using C BPOPS103

The phases in software development process (as shown in Figure 3.3) can be summarized as below:

Fig 3.3 Phases of Software development life cycle

Requirements Analysis: In this phase, users‟ expectations are gathered to know why the program/software
has to be built. Then all the gathered requirements are analyzed to pen down the scope orthe objective of the
overall software product. The functionality, capability, performance, availability of hardware and software
components are all analyzed in this phase.

Design: The requirements documented in the previous phase acts as an input to the design phase. In the
design phase, a plan of actions is made before the actual development process could start. This plan will be
followed throughout the development process. Moreover, in the design phase the core structure of the
software/program is broken down into modules. The solution of the program is then specified for each
module in the form of algorithms, flowcharts, or pseudo codes. The design phase, therefore, specifies how
the program/software will be built.

Implementation: In this phase, the designed algorithms are converted into program code using any of the
high level languages. The particular choice of language will depend on the type of program like whether it
is a system or an application program. While C is preferred for writing system programs, Visual Basic might
be preferred for writing an application program. The program codes are tested by the programmer to ensure
their correctness. This phase is also called construction or code generation phase as the code of the software
is generated in this phase. While constructing the code, the development team checks whether the
Module-1
Principles of Programming using C BPOPS103

software is compatible with the available hardware and other software components that were mentioned in
the Requirements Specification Document created in the first phase.

Testing: In this phase, all the modules are tested together to ensure that the overall system works well as a
whole product. Although individual pieces of codes are already tested by the programmers in the
implementation phase, there is always a chance for bugs to creep in the program when the individual modules
are integrated to form the overall program structure. In this phase, the software is tested using a large number
of varied inputs also known as test data to ensure that the software is working as expected by the users‟
requirements that were identified in the requirements analysis phase.

Software Deployment, Training, and Support: After the code is tested and the software or the program
has been approved by the users, it is then installed or deployed in the production environment. Software
Training and Support is a crucial phase which is often ignored by most of the developers. Program designers
and developers spend a lot of time to create software but if nobody in an organization knows how to use it
or fix up certain problems, then no one would like to use it. Moreover, people are often resistant to change
and avoid venturing into an unfamiliar area, so as a part of the deployment phase, it has become very crucial
to have training classes for the users of the software.

Maintenance: Maintenance and enhancements are ongoing activities which are done to cope with newly
discovered problems or new requirements. Such activities may take a long time to complete as the
requirement may call for addition of new code that does not fit the original design or an extra piece of code
required to fix an unforeseen problem. As a general rule, if the cost of the maintenance phase exceeds 25%
of the prior-phases cost then it clearly indicates that the overall quality of at least one prior phase is poor.
In such cases, it is better to re-build the software (or some modules) before maintenance cost is out of control.

3.4 Program Design Tools: Algorithms, Flowcharts, Pseudocodes

3.4.1 Algorithms
In general terms, an algorithm provides a blueprint to writing a program to solve a particular problem. It is
considered to be an effective procedure for solving a problem in a finite number of steps. That is, a well-
defined algorithm always provides an answer, and is guaranteed to terminate.

Algorithms are mainly used to achieve software re-use. Once we have an idea or a blueprint of a solution,
we can implement it in any high-level language, such as C, C++, Java, and so on. In order to qualify as an
algorithm, a sequence of instructions must possess the following characteristics:
✓ Be precise
Module-1
Principles of Programming using C BPOPS103

✓ Be unambiguous
✓ Not even a single instruction must be repeated infinitely
✓ After the algorithm gets terminated, the desired result must be obtained

Control Structures used in Algorithms


An algorithm has a finite number of steps and some steps may involve decision-making and repetition.
Broadly speaking, an algorithm can employ any of the three control structures.
1. Sequence
2. Decision
3. Repetition.

Sequence
Sequence means that each step of the algorithm is executed in the specified order. An algorithm to add two
numbers is given below. This algorithm performs the steps in a purely sequential order.

Step 0: Start
Step 1: Input the first number as A
Step 2: Input the second number as B
Step 3: Set SUM = A + B
Step 4: Print SUM
Step 5: End

Decision
Decision statements are used when the outcome of the process depends on some condition. For example, if
x=y, then print “EQUAL”. Hence, the general form of the if construct can be given as
if condition then process
An algorithm to check the equality of two numbers is shown below.
Step 0: Start
Step 1: Input the first number as A
Step 2: Input the second number as B
Step 3: If A = B Then Print "EQUAL" else PRINT "NOT EQUAL"
Step 4: End
Module-1
Principles of Programming using C BPOPS103

Repetition
Repetition, which involves executing one or more steps for a number of times, can be implemented using
constructs such as while, do-while, and for loops. These loops execute one or more steps until some condition
is true. An algorithm that prints the first 10 natural numbers as shown below.

Step 0: Start
Step 1: [INITIALIZE] SET i = 0, n = 10
Step 2: Repeat Step while i<=n
Step 3: PRINT i
Step 4: Set i= i + 1
Step 5: End

Selecting the Most Efficient Algorithm

The time complexity of an algorithm is basically the running time of a program as a function of the input
size. Similarly, the space complexity of an algorithm is the amount of computer memory that is required
during the program execution as a function of the input size.

3.4.2 Flowcharts
A flowchart is a graphical or symbolic representation of a process. It is basically used to design and document
virtually complex processes to help the viewers to visualize the logic of the process, so that they can gain a
better understanding of the process and find flaws, bottlenecks, and other less obvious features within it.
When designing a flowchart, each step in the process is depicted by a different symbol and is associated with
a short description. The symbols in the flowchart are shown below.
Module-1
Principles of Programming using C BPOPS103

Figure 3.2 Symbols of flowchart

The symbols of a flowchart include:


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

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


Module-1
Principles of Programming using C BPOPS103

Example2: Draw a flowchart to determine the largest of three numbers.

3.4.3 Pseudocodes
Pseudocode is a compact and informal high-level description of an algorithm that uses the structural
conventions of 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 sub-routines.
Pseudocodes are an outline of a program that can be easily 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.
Module-1
Principles of Programming using C BPOPS103

The sole purpose of pseudocodes is to enhance human understandability of the solution. They are
commonly used in textbooks and scientific publications for documenting algorithms, and for sketching out
the program structure before the actual coding is done. This helps even non-programmers to understand the
logic of the designed solution. There are no standards defined for writing a pseudocode, because a
pseudocode is not an executable program. Flowcharts can be considered as graphical alternatives to
pseudocodes, but require more space on paper.
Example 1.3
Write a pseudocode for calculating the price of a product after adding sales tax to its original price.
Solution
1. Read the price of the product
2. Read the sales tax rate
3. Calculate sales tax = price of the item × sales tax rate
4. Calculate total price = price of the product + sales tax
5. Print total price
6. End
Variables: price of the product, sales tax rate, sales tax, total price

Example 1.4
Write a pseudocode to read the marks of 10 students. If marks are greater than 50, the student passes, else
the student fails. Count the number of students who pass and the number who fail.
Solution
1. Set pass to 0
2. Set fail to 0
3. Set no of students to 0

4. WHILE no of students < 10


a. input the marks
b. IF marks >= 50 then
Set pass = pass + 1
ELSE
Set fail = fail + 1
ENDIF
ENDWHILE
5. End
Variables: pass, fail, no of students, marks

PSEUDOCODES

➢ Pseudocode is an informal list of steps in English like statements which is intended for human reading.
➢ It is used in planning of computer program development, for sketching out the structure of the program
before the actual coding takes place.
Module-1
Principles of Programming using C BPOPS103

Advantages:

1. It can be written easily


2. It can be read and understood easily
3. Modification is easy

Disadvantages:
1. There is no standard form.
2. One Pseudocode may vary from other for same problem statement.

Examples:

Pseudocode: Addition of two numbers Pseudocode: Area of rectangle

1. Begin 1. Begin
2. Read two numbers a, b 2. Read the values of length, breadth
3. Calculate sum = a+b 3. Calculate area = l x b
4. Display sum 4. Display area
5. End 5. End

3.5 Types of Errors

1. Run Time Errors: It occurs when the program is being run executed. Such errors occur when the
program performs some illegal operations like
✓ Dividing a number by zero
✓ Opening file that already exists
✓ Lack of free memory space
✓ Finding Square of logarithm of negative numbers
Run time errors may terminate program execution

2. Compile Time Errors: It occurs at the time of compilation of the program.


Such errors can be classified as follows:
i. Syntax errors: They generated only when rules of programming language are violated
ii. Semantic errors: Which may comply with the rules of the programming language but are not
Module-1
Principles of Programming using C BPOPS103

meaningful to the complier

3. Logical Errors: Logical errors are the errors in the program code that result in unexpected and
undesirable output.
4. Linker Errors: These errors occur when the linker is not able to find the function definition for a given
prototype.
Module-1
Principles of Programming using C BPOPS103

CHAPTER 4
Introduction to C

4.1 Introduction
The programming language c was developed in the early 1970‟s by Dennis Ritchie at Bell Laboratories
to be used by the UNIX operating system. It was renamed „C‟ because many of its features were derived
from an earlier language. C was designed for developing portable application software.
4.1.1 History of C

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


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

Examples of C:

• Operating system
• Language compilers
• Assemblers
• Text editors
• Databases

4.1.2 Characteristics of C
➢ C is high level language
➢ C makes extensive use of function calls
➢ C is well structured Programming
➢ C is Stable Language
➢ C facilitates low level language
➢ C is Portable language
➢ C is easy to learn.
➢ C is core language
➢ C is extensible language
➢ C is often treated as second best language
➢ C is a general purpose language.
➢ It can extend itself.

4.1.3 Uses of C
➢ C language was primarily used for system programming
➢ C has been widely accepted by professionals that compilers, libraries and interpreters of
other languages written in c.
➢ C is widely used to implement end-user applications
➢ C can be used as intermediate language
Module-1
Principles of Programming using C BPOPS103

4.2 Structure of ‘C’ Program

C program consists of different sections. The structure of C program is as shown below.


➢ Documentation Section: It consists of a set of comment line giving the name of the program, the
author and other details. Compiler ignores these comments. There are two formats:
a) Line comments //Single line comment
b) Block comments /*Multi line comment*/
➢ Link Section: It provides instruction to the compiler to link functions from system library.
➢ Definition Section: It defines all symbolic constants.
➢ Global Declaration Section: The variables which are used in more than one function are called global
variables and are declared in this section.
➢ main( ) Section: Every „C‟ program has one main( ) function and it contains two parts:
i. Declaration Part: Here, all the variables used are declared.
ii. Executable Part: Here, it contains at least one executable statement.

The main( ) function is enclosed within flower brackets and the statements ends with semicolon.

➢ Sub-program Section: It contains all the user defined functions that are called by main( ) function.

Documentation section
Link section
Definition section
Global declaration section
main( ) Section
{
Declaration part
Executable part
}
Sub program section
Function 1
Function 2
-
-
Function n
Module-1
Principles of Programming using C BPOPS103

Example:

//Addition of two numbers


#include<stdio.h>
void main( )
{
int a, b, sum;
printf(“Enter two numbers\n”);
scanf(“%d%d”, &a, &b);
sum = a + b;
printf(“The sum is %d”, sum);
}

4.3 Writing the first ‘C’ Program


#include <stdio.h>
int main()
{
// printf() displays the string inside quotation
printf("Hello, World! \n");
return 0;
}

Output

Hello, World!

How "Hello, World!" program works?


➢ The #include is a preprocessor command that tells the compiler to include the contents of stdio.h (standard
input and output) file in the program.
➢ The stdio.h file contains functions such as scanf() and printf() to take input and display output
respectively.
➢ If you use the printf() function without writing #include <stdio.h>, the program will not compile.
➢ The execution of a C program starts from the main() function.
➢ printf() is a library function to send formatted output to the screen. In this program, printf() displays Hello,
World! text on the screen.
➢ The return 0; statement is the "Exit status" of the program. In simple terms, the program ends with this
statement.
Module-1
Principles of Programming using C BPOPS103

4.4 Files used in C Program

4.4.1 Source code files


It contains source code of the program. The extension of any C source code file is .c. This file contains
source code that defines the main function is the starting point of execution when you successfully
compile and run the program.

4.4.2 Header files


When working with large projects, it is often desirable to separate out certain subroutines from the
main() function of the program. There also may be case that the same subroutine has to be used in
different programs. This is used by .h extension
Standard Header files are as follows:

stdio.h-for standard input and output functions


stdlib.h-for some miscellaneous functions like exit() function
string.h-for string handling functions
math.h-for mathematical functions like sqrt(), pow(), fabs()
Module-1
Principles of Programming using C BPOPS103

conio.h- for clearing screen like clrscr() function


alloc.h- ofr dynamic memory functions

4.4.3 Object files


Object files are generated by the compiler as a result o processing the source code file. Object code file
contains a binary code of the source code. It is used with filename .obj extension.

4.4.4 Binary Executable files


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

4.5 Compiling and Executing a C Program


The compiler translates a source code into an object program. The object code contains the machineinstructions
for the CPU and calls to the operating system API(Application program Interface).

The object file is processed with another special program called a linker. While there is a different compiler
for every individual language, the same linker is used for object files in which new program was written. The
output of linker is an executable or runnable file. The over view of compilation and execution of c program
as shown below.

The compilation process is shown below with two steps.


The first step, preprocessor program reads the source file as text, and produces another text file as output.
Source code lines which begin with the #symbol are actually not written in C but in the preprocessor language.
The output of preprocessor text file which does not contain any preprocessor statements. This file is ready to
be processed by the compiler.
The linker combines the object file with library routines to produce the final executable file.

In modular programming, the source code is divided into two or more source files. All these source files
are compiled separately thereby producing multiple object files. Object files are combined by the linker
to produce an executable file as shown below.
Module-1
Principles of Programming using C BPOPS103

4.6 Using Comments


C supports two types of comments.
1. Single line Comment
2. Multiline Comment

Single Line comment:


The symbol which is used for the single line comment is //.
A line comment can be replaced anywhere on the line and it does not require to be specifically ended as
the end of the line automatically ends the line

Multiline Comment:
The symbol which is used for the multiline comment is /* and */
The type of the comment is a block comment. The multiple lines are commented by using the above
symbol. Note that commented statements are not executed by the compiler.

4.7 C – Tokens

➢ Tokens are the building blocks in a C language


➢ It is also called as lexical unit.
➢ The smallest individual unit in „C‟ program is called as C-Token.
➢ 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


A C character set defines the valid characters that can be used in a source program. The basic C character
set are:
1. English Alphabetss:
Uppercase Letters: A, B, C,…., Z
Lowercase Letters: a, b, c,….., z
Module-1
Principles of Programming using C BPOPS103

2. Digits: 0, 1, 2,….., 9
3. Special characters: ! , @. #, $, %, *, (, ),}, {, ;,:,”,‟,?,>,<,/,,,.,|,\,&,^, etc
4. White spaces: These characters are used to print a Blank space on the screen, Horizontal tab
space (\t), carriage return, new line character (\n), form feedcharacter.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 int struct break do


else long switch goto sizeof if
case enum register typedef default
char extern return union volatile
const float short unsigned while
continue for signed void static

4.10 Identifiers

➢ It help us to identify the data and other objects in the program


➢ These are the names given to Program elements such as variables, functions, arrays and macros etc.
➢ It may be consists of sequence of letters, numerals or underscores.

4.10.1 The Rules for Forming Identifier Names


➢ It cannot include any special symbol characters or punctuation marks (like #,$^?. And etc) apart from
underscore.
Module-1
Principles of Programming using C BPOPS103

➢ There cannot be Two successive Underscore symbol(_)


➢ Key words cannot be used as identifiers
➢ It must contain only alphabets (A to Z, a to z), numbers (0 to 9) and underscore ( _ ).
➢ It must start with alphabet or underscore but not numeric character.
➢ It should not have any space.
➢ Identifiers are case sensitive.
➢ Maximum length of an identifier is 31 characters.
Examples:
Valid Identifiers: integer, minimum, sum_total, row1, _cpps
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 Data types in C

C language provides few basic data types as shown in the below table.

The detailed data types are given below.


Module-1
Principles of Programming using C BPOPS103

✓ Data type defines the types of data that is stored in a variable.


✓ There are 3 types:
i. Primary/ Built-in/ Fundamental data type → int, float, double, char, void
ii. Derived data type → array, structure
iii. User defines data type → enum, typedef

❖ Primary/ Built-in/ Fundamental data type: These are the built in data types available in C. There are
5 types. Namely:
1. Integer (int)
2. Floating point (float)
3. Character (char)
4. Double precision floating point (double)
5. Void (void)
1. Integer type:
➢ It is used to store whole numbers.
➢ The keyword int is used to declare variable of integer type.
➢ Int type takes 2B or 4B of storage depending on machine size.
➢ The classes of integer are:
Module-1
Principles of Programming using C BPOPS103

Unsigned Signed
Data type Keyword Size Data type Keyword Size
Short Integer short int 1B Signed short integer signed short int 1B
Integer int 2B Signed integer signed int 2B
Long Integer long int 4B Long integer long int 4B

2. Floating point data type:


➢ It is used to store decimal numbers.
➢ The keyword float is used to declare variable of floating point data type.
➢ Float type takes 4B or 8B of storage depending on machine size.
➢ It can be expressed in fractional or exponential form.

Data type Keyword Size


Floating point float 4B
Double double 8B
Long double long double 10B

3. Double:
➢ It is used to store double precision floating point numbers.
➢ The keyword double is used to declare variable of floating point data type.
➢ Double type takes 8B of storage.
➢ Double precision is related to accuracy of data.

4. Char:
➢ It is used to store character type of data.
➢ The keyword char is used to declare variable of character type.
➢ Char type takes 1B of storage.

5. Void:
➢ It is a special data type that has no value.
➢ It doesn‟t have size.
➢ It is used for returning the result of function that returns nothing.
Module-1
Principles of Programming using C BPOPS103

4.12 Variables
A variable is defined as a meaningful name given to a data storage location in computer memory.
When using a variable, we actually refer to the address of the memory where the data is stored.
The variable value will be changed during the execution of program.
✓ A variable is a name given to memory location whose value changes during execution.

✓ Declaration:

Syntax: datatype variable_list;


Where, datatype → Any built in data type
variable_list → Identifiers that specifies variable name.

Example: int a;
Where, int is the built in data type
a is variable of type int.

✓ Initialization:

Syntax: datatype variable_name = value;


Where,
datatype → Any built in data type
variable_name → Identifier that specifies variable name.
value → The data which will be stored in variable name.
Example: int a = 10;
Where,
int → data type
a → variable name
10 → value
Principles of Programming using C BPOPS103 Module 1

4.12.1 Numerical Variables


It can be used to store either integer values or floating values. While integer value whole number without
a fraction part or decimal point, a floating point value can have a decimal point.
They are also may be associated with modifiers, such as short, long, signed and un-signed numeric
variables.

4.12.2 Character variables


Character variables are just single characters enclosed within single quotes. These characters variables
could be any character from the ASCII character set-letters („a‟, „A‟), numerals („2‟) or special
character(„&‟)

4.12.3 Declaring variables


To declare a variable, specify the data type of the variable followed by its name. The data type indicates
the kind of values that variable will store. Variable declared in a program always ends with semicolon.
Syntax: datatypename variablename;
Example: int emp_num;
float salary;
char grade;
double balance amount;
unsigned short int acc_num;

4.12.3 Initializing variables


While decarting variables, we can initialize them with some value.
Syntax: datatypename variablename= value;
Example: int emp_num=7;
float salary=2156.35;
char grade=‟A‟;
double balance amount=100000000;

4.13 Constants
➢ Constants are the values that don‟t changes during the execution of a program.
➢ A constant is an explicit data value specified by the programmer.
➢ Constants are used to define the fixed values.

Integer Constant
Numeric
Constant
Real Constant

Constant
Single Character
Constant
Character
Constant
String Constant

Figure 3: Types of Constants

28
Principles of Programming using C BPOPS103 Module 1

✓ Numerical Constant

Integer Constant: These are the numbers without decimal part.


Decimal: It is an integer constant consisting of numbers from 0-9. It can be preceded by + or –
Octal: It is an integer constant consisting of numbers from 0-7. It is preceded by o
Hexadecimal: It is an integer constant consisting of numbers from 0-9, A-F (A=10, B=11, C=12,
D=13, E=14, F=15). It is preceded by 0x

Real Constant:

▪ These are the numbers with decimal part.


▪ These are also called as floating point constant.
▪ The floating values can be identified by the suffix „F‟ or „f‟
▪ It can be expressed in exponential form.
Ex: 21.5, 2.15 x 102 → 2.15e2

✓ Character Constant

Single Character Constant:


These are the values enclosed within single quotes.
Each character have an integer value called as ASCII (American Standard Code for Information
Interchange) → A: 65, a: 97
Printable Character: All characters are printable except backslash(\) character or escape
sequence.
Non-Printable Character: The characters with backslash (\) are non printable. Ex: \n, \t

String Constant:
A group of characters together form string.
Strings are enclosed within double quotes.
They end with NULL character (\0).
Ex: “GCEM” →

G C E M \0

NOTE:
✓ Qualified Constant/ Memory Constant: These are created by using “const” qualifier. Const means
that something can only be read but not modified.
Syntax: const datatype variable_name = value;
Ex: const int a = 10;
29
Principles of Programming using C BPOPS103 Module 1

const float pi = 3.14;

✓ Symbolic Constants/ Defined Constant: These are created with the help of define
preprocessor directive.
Ex: #define PT 3.142
➢ During processing the PI in the program will be replaced with 3.142.
➢ The name of constant is written in uppercase just to differentiate from the variables.

✓ Enumeration Constant: An enumeration is a list of constant integer values. Names in


enumeration must be distinct. The keyword used is “enum”.
Ex: enum days = {Sun, Mon, Tue, Wed, Thu, Fri, Sat}
Sun → 1, Mon → 2, ……., Sat → 7

Strings

➢ A group of characters together form string.


➢ Strings are enclosed within double quotes.
➢ They end with NULL character (\0).
Ex: “GCEM” →

G C E M \0

14.4 Input Output statements in C

14.4..1 Formatted Input Output Statements

scanf()
✓ Formatted input refers to an input data that has been arranged in particular format.
✓ Ex: 152 Rajesh
✓ In the above example the first part contains integer and the second part contains characters. This is
possible with the help of scanf function.

Syntax: scanf(“control string”, arg1, arg2,…..,argn);

where
➢ The control string specifies the field form in which data should be entered
➢ The arguments arg1, arg2,…..,argn specifies the address of the location where the data is
stored.
✓ The width of the integer number can be specified using %wd.

Example-2:
– scanf(“%2d %2d”, &a, &b);
%2d→ two digit integer
%2d → two digit integer 4567 25

30
Principles of Programming using C BPOPS103 Module 1

a=45 b=67
Note: 25 is not at all stored

✓ The input field may be skipped using * in the place of field width.
Example-3:
– scanf(“%2d %*d %2d”, &a, &b);
%2d→ two digit integer
%*d → skip this integer 45 25 63
a=45
25 is skipped b=63
✓ The scanf function can read single character or more than one character using %c or %s.

Rules for scanf:


➢ Each variable to be read must have a specification
➢ For each field specification, there must be a address of proper type.
✓ Never end the format string with whitespace. It is a fatal error.
✓ The scanf will read until:
▪ A whitespace character is found in numeric specification.
▪ The maximum number of characters have been read
▪ An error is detected
▪ The end of file is reached
✓ Any non-whitespace character used in the format string must have a matching character in the
user input.

❖ The below table shows the scanf format codes commonly used.

Code Meaning
%c Read a single character
%d Read a decimal integer
%e, %f, %g Read a floating point
value
%h Read a short integer
%i Read a decimal integer
%o Read a octal integer
%s Read a string
%u Read an unsigned
decimal integer
%x Read a hexadecimal
integer
%[ ] Read a string of word
The l can be used as a prefix for long integer. Ex: %ld
printf()

The printf function is used for printing the captions and results.

Syntax: printf(“control string”, arg1, arg2, ….., argn);

Where

31
Principles Of Programming Using C BPOPS203 Module 1

➢ The control string specifies the field form in which data should be printed.
➢ The arguments arg1, arg2,…..,argn specifies the location where the data is stored
to beprinted on the screen

✓ Control string contains three types of items:


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b.

❖ The below table shows the printf format codes commonly used.
Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floating point value in
exponent form
%f Print a floating point value
without exponent
%g Print a floating point value
with or without exponent
%h Print a short integer
%i Print a decimal integer
%o Print a octal integer
%s Print a string
%u Print an unsigned decimal
integer
%x Print a hexadecimal integer
%[ ] Print a string of word

The l can be used as a prefix for long integer. Ex: %ld


➢ General syntax of field-width/size for different data types:

• %wd → Example: %6d

• %w.pf → Example %6.2f

• %w.ps → Example %10.4s


– w means total field size/width
– P means precision (tells how many decimal places to be printed in case of float) and
– How many characters to be printed in case of strings

You might also like