Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Module 1 Notes

The document provides an overview of the principles of programming using C, focusing on the characteristics of computers, the stored program concept, and the evolution of computer generations from vacuum tubes to ultra-large scale integration. It classifies computers into categories such as supercomputers, mainframes, minicomputers, and microcomputers, detailing their features and applications. Additionally, it discusses various applications of computers in fields like e-business and bioinformatics.

Uploaded by

rawatprachi13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module 1 Notes

The document provides an overview of the principles of programming using C, focusing on the characteristics of computers, the stored program concept, and the evolution of computer generations from vacuum tubes to ultra-large scale integration. It classifies computers into categories such as supercomputers, mainframes, minicomputers, and microcomputers, detailing their features and applications. Additionally, it discusses various applications of computers in fields like e-business and bioinformatics.

Uploaded by

rawatprachi13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

BPOPS103 Principles of Programming Using C

Module 1
Introduction to C
A computer, in simple terms, can be defined. As an electronic device. That is designed to accept data,
perform their arithmetical mathematical and logical operations at high speed, and output the result.

Characteristics of computer.
1. Speed:
 Computer can perform millions of operations per second.
 The speed of the computer is usually given in nanoseconds and 1 picoseconds. (1 nanosecond
is equal to 1 into 10 to the power of -9 and one picosecond is equal to 1 into 10 to the power
of -12 seconds.)
2. Accuracy:
A computer is a very fast, reliable and robust electronic device. It always gives accurate results
provided the correct data and the set of instructions or input to it. Hence, in the event of an error,
only the user who has fed the incorrect data or the program needs to held responsible. If the input
is wrong, then the output will also be erroneous. In the computer terminology. It is known as
garbage in, garbage, out (GIGO.)
3. Automation:
Computers or automobile 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 instruction.
4. Diligence:
Unlike humans, a computer never gets tired of a Repetitive task. It can continuously work for
hours without creating errors.
5. Versatile:
Versatility Is the quality of being flexible. Today computers are used in our daily life in different
fields. For example, they are used as personal computer (PCs ) for home use, for business-
oriented task, weather forecasting, space exploration, teaching, railways, banking, medicine and
so on indicating that computer can perform the different tasks simultaneously.
6. Memory:
Similar to humans, computers also have memory just the way we cannot store everything in our
memory and need secondary media such as notebooks to record certain important things.
Computers also have internal or primary memory as well as external or secondary memory.
While the internal memory for computers is very expensive and limited in size, the secondary
memory is cheaper and bigger capacity.
7. No IQ:
Although the trend today is to make computers intelligent by including artificial intelligence (AI)
in them, they do not have any decision-making abilities of their own. That is, their IQ level is
zero. They need guidance to perform various tasks.
8. Economically:

BIT,B‘lore 1
BPOPS103 Principles of Programming Using C

Using computers also reduce manpower requirements and lead 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.

Stored Program Concepts


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

BIT,B‘lore 2
BPOPS103 Principles of Programming Using C

Computer generations:
Generation in computer terminology is changed in technology a computer is being used. There are five
generations of computer.
1. First generation of computer ( 1940 - 1956 )- Vacuum tubes.
 This generation computer used thousands of vacuum tubes for circuitry for CPU (Central
Processing Unit).
 Memory requirements were met by magnetic drums.
 It took a lot of space, consume enormous amount of power and generated a lot of heat. Also was
extremely expensive.
 These computers used machine language
 Some computers of this generation were: ENIAC, EDVAC, UNIVAC, etc.
 Program input was provided by punch cards and output were produced on papers.
2. Second generation of computer ( 1956 - 1963 )- Transistors.
 Transistors were used that were cheap, consume less power, more compact in size, more
reliable and faster.
 Magnetic cores were used as the primary memory and magnetic tape and magnetic disk as
secondary storage device.
 These computers used assembly language. (Programmer could specify words and symbols as
instructions instead of zeros and ones).
 Some computers of this generation were IBM 1620, IBM 7094.
3. Third generation computer ( 1964 to 1971 )- Integrated circuits.

BIT,B‘lore 3
BPOPS103 Principles of Programming Using C

 Single IC has many transistors, resistors and capacitors along with the associated circuitry.
 This development made computers smaller in size, reliable and efficient.
 In this generation remote processing, time sharing multi programming operating systems were
used.
 High level language (FORTRON, COBOL, BASIC, PASCAL, ALGOL) were used during this
generation
 Keyboard and monitor were used to interact with user.
 Memory capacity increase sustainability by the use of hard disk for secondary memory
 Some computers of this generation were IBM 360 series, Honeywell 6000 Series and Personal
Data Processor.
4. Fourth generation computer ( 1971 - 1980): Microprocessor.
 Used very large scale integrated (VLSI ) Circuits having about 5000 transistors and other circuit
elements with their associated circuits on a single chip.
 The microprocessor launched the 4th generation of computer, with thousands of integrated
circuits built onto a single silicon chip.
 Computers became more powerful, compact, reliable and affordable.
 As a result. It gave rise to personal computer revolution, laptops and smartphones offering
gigabytes of memory compared to few megabytes.
 In this generation time-sharing, real-time networks, distributed operating system were used. The
high level languages like C,C++, DBase etc were used in this generation
 4th generation computer also saw the development of graphical user interface, the mouse and
handheld devices.
5. Fifth generation computers ( 1982 - till date)
 With ULS (Ultra Large Scale integration) Technology microprocessor chips having 10 million
electronic components were manufactured.
 This generation is based on parallel processing hardware and AI.
 AI is an emerging branch in computer science, which interprets the mean and method of making
computers think like human beings
 All the high level languages like C&C++, Java, .NET etc, are used in this generation.
 Neural networks and expert systems have to be Developed.
Classification of computers.

BIT,B‘lore 4
BPOPS103 Principles of Programming Using C

1. Super Computers:
 Super computer is the fastest, most powerful, and most expensive computer.
 Super Computers were first developed in 1980s to process large amount of data and to solve
complex scientific problems
 A single super computer can support thousands of users at the same time.
 Super Computers are mainly used for weather forecasting, nuclear energy research, aircraft
design, automotive design, online banking, controlling industrial units, etc.
2. Mainframe computers.
 Mainframe is a very large in size and is an expensive computer capable of supporting hundreds
or thousands of users simultaneously.
 The processor speed is measured in MIPS ( millions of instruction per seconds)
 Used for online transactions.
 Capability to handle large amount of data makes mainframe suitable for use in government,
banks and financial institutions.
 There are basically two types of terminals that can be used with mainframe systems are:
1. Dumb terminal
Dumb terminals consist of only a monitor and a keyboard (or mouse) They do not have their own
CPU, Memory and the use of mainframe systems CPU and storage devices.
2. Intelligent terminal
Intelligent terminals have their own processor and thus can perform some processing operations.
They do not have their own storage space.
3. Mini computer.
 It is a multiuser computer system capable of supporting hundreds of users simultaneously.

BIT,B‘lore 5
BPOPS103 Principles of Programming Using C

 Mini computers are smaller, cheaper and slower than mainframes. They are called mini
computers because they were the smallest computer of their times. Also known as midrange
computers. The capability of mini computers fall between mainframe and PCs.
 The first mini computer was introduced by Digital Equipment Corporation. (DEC) in mid 1960.
 The mini computers are used in small organizations or at department of a large one.
4. Micro computers.
 Micro computers, commonly known as PCs, are very small and cheap.
 The Micro Computer or PC is introduced by Apple and endorsed by IBM. This is a single user
machine powered by single chip microprocessor.
 They are very powerful machines having gigabytes of memory.
 They are both used in stand alone mode and in a network.
 A micro computer takes the form of desktop, notebook (laptop) or a notebook (smaller laptop).
PCs today are powered by three types of OS. Windows ( 7, 8 or 10.) Mac OS X (Apple) and
Linux.
 They are used for engineering and scientific application and for software development.
 PCs can be classified into following categories.
1) Desktop: The system unit of the desktop PC can be placed flat on a desk or table. It is widely
used in homes and offices.
2) Laptop: Laptops are small microcomputers that can easily fit inside a briefcase. They are very
handy and can easily be carried from one place to another. 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).
3) Workstation: 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.
4) Networked 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.
5) Handheld Computers: The mid-1990s witnessed a range of small personal computing devices
that are commonly known as handheld computers, or mobile computers. 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:
a) Smartphones: These are web enabled phones, 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. Smartphones run an advanced mobile operating system that
enables it to run various applications, The four major mobile operating systems are iOS,
Android, BlackBerryOS, and Windows Mobile. Smartphones also have a CPU, more storage
space, more memory, and 4 larger screen than a regular cell phone.

BIT,B‘lore 6
BPOPS103 Principles of Programming Using C

b) Tablet PCs: It 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. Some operating systems that are used in tablets are
Android Jellybean (an open-source operating system built by Google), Windows 8, and iOS
(developed by Apple).
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

Applications of Computer:
Let us discuss how computers are being effectively utilized to perform important tasks.
1) 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.
2) 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. It allows user to access e-mail, chat s/w‘s, video conferencing tools etc.
3) Digital video or audio composition: Computers make audio or video composition and editing
very simple. This has drastically reduced the cost of equipment to compose music or make a
film. Graphics engineers use computers for developing short or full-length films and creating 3-
D models and special effects in science fiction and action movies.
4) Desktop publishing: Desktop publishing software enables us to create page layouts for entire
books.

Let us now have a look at the different areas where computers are being widely utilized.
1) 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.
The following are techniques in which e-commerce helps users to conduct business transactions.
a) 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

BIT,B‘lore 7
BPOPS103 Principles of Programming Using C

their websites, they provide features such as catalogues, interactive order processing system,
secure electronic payment system, and online customer support.
b) 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.
c) 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.
d) Electronic banking: Electronic banking, also known as cyberbanking or online banking,
supports various banking activities conducted from home, a business, or on the road instead
of a physical bank location.
2) Bioinformatics: Bioinformatics is the application of computer technology to manage large
amount of biological information. Computers are used to collect, store, analyse, and integrate
biological and genetic information to facilitate gene-based drug discovery and development.
Bioinformatics helps scientists to store the DNA information in huge databases, retrieve it as and
when required, and analyse it to grow and develop new organisms.
Scientists also use bioinformatics to identify diseases and discover drugs for them.
3) Health care: he following are areas in which computers are extensively used in the health care
industry.
a) Storing records: computers are first and foremost used to store the medical records of
patients. the entire medical history of patients is easily accessible. Since the records are
electronically stored, they can be easily shared between different doctors who are treating
same patients. Use of computers also saves patients‘ money by reducing duplication of tests
and procedures.
b) 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.
c) Better diagnosis and treatment: Computers help physicians make better diagnoses and
recommend treatments. Doctors sitting in hospitals can monitor their t sitting in their homes
by using computer-based systems.
4) Geographic Information System and Remote Sensing: A geographic information system (GIS)
is a computer based tool for mapping and analysing earth‘s features. It integrates database
operations and statistical analysis to be used with maps. GIS manages location based information
and provides tools for display and analysis of statistics such as population count, types of
vegetation, and economic development opportunities. Such type of information helps to predict
outcomes and plan strategies.

Remote sensing is the science of taking measurements of the earth using sensors on airplanes or
satellites. These sensors collect data in the form of images, which are then analysed to derive
useful information. The key feature of remote sensing is that it acquires information about an
object without making physical contact with it. Remote sensing can be applied in the following
areas to collect data of dangerous or inaccessible areas for the following:

BIT,B‘lore 8
BPOPS103 Principles of Programming Using C

 Monitoring deforestation in areas like the Amazon Basin


 Studying features of glaciers in Arctic and Antarctic regions
 Analysing the depth of coastal and ocean areas
 Studying land usage in agriculture
 Examining the health of indigenous plants and crops
 Determining the prospect for minerals
 Locating and measuring intensity of earthquakes (after they had occurred) by comparing the
relative intensity and precise timings of seismograms collected from different locations.

5) 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.
The applications include the following:
a) 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 analysing the atmospheric processes to project how the atmosphere will
evolve.
b) 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,
c) 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.
d) Nuclear meteorology: Nuclear meteorology studies the distribution of radioactive aerosols
and gases in the atmosphere.
e) Maritime meteorology: Maritime meteorology is the study of air and wave forecasts for
ships operating at sea.
6) 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. Multimedia and animation is used to add special effects in movies. In education,
multimedia is used to prepare training courses.
7) 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.
8) 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.
9) 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.
10) 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. Also used to research about hotels in an area, reserve
rooms, or to rent a car.

BIT,B‘lore 9
BPOPS103 Principles of Programming Using C

11) Simulation: Supercomputers that can process enormous amount of data are widely used in
simulation tests.
12) Astronomy: Spacecrafts are usually monitored using computers by keeping a continuous record
of the voyage and of the speed, direction, fuel, and temperature, and also suggest corrective action
if the vehicle makes a mistake.
13) Education: Computers can also be used as a teaching aid by teachers, for providing instruction
materials.
14) 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).
15) Robotics: Robots are computer-controlled machines mainly used in the manufacturing process in
extreme conditions where humans cannot work.
16) Decision Support Systems: Computers help managers to analyse their organization's data to
understand the present scenario of their business, view the trends in the market, and predict the
future of their products. Managers also use decision support systems to analyse market research
data, to size up the competition, and to plan effective strategies for penetrating their markets.
17) Expert Systems: Expert systems are used to automate the decision-making process in a specific
area.

Basic organization of computer:

A computer is an electronic device that basically performs five major operation.


1. Accepting data or instruction
2. Storing data.
3. Processing data
4. Displaying data.
5. Controlling and coordinating all operations inside a computer.

 Input.
 This is a process of entering data instruction into the computer.
 The data and instructions can be entered by using different input devices such as keyboard, most
common scanner, The track ball, Etc.

BIT,B‘lore 10
BPOPS103 Principles of Programming Using C

 Note that computers understand binary languages, which consist of only two symbols, 0 and 1.
So it is the responsibility of the input device 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 new line A computer has two type of storage areas.
1. Primary storage
 Primary storage, also known as main memory, is the storage area that is directly accessible
by the CPU at very high speed.
 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.
 RAM and ROM are the examples of primary storage.

RAM.
 It's stands for Random Access Memory.
 It is a temporary memory. That means it is used to store information that is used
immediately.
 Once the computer is turned off, the data will be deleted. With the help of RAM, computers
can perform multiple tasks like loading application, browsing the web tasks, editing the
spreadsheet, etc.
 There are two types.
o SRAM, (static, RAM) volatile. stores until system is on
o DRAM. (Dynamic ramp) store binary bits in the form of electrical charges.

ROM:
 It stands for Read only memory. The data stored in these devices are nonvolatile, that is, once
the data stored in the memory cannot be modified or deleted.
 The memory form, which will only read but cannot write.
 The information is stored permanently
 There are three types.
o PROM. (Programmable ROM.) data cannot be altered.
o EPROM, (Erasable, Programmable ROM) Possible to erase the information.
o EEPROM, (electrically erasable ROM) nonvolatile memory used in computers,
usually integrated in microcontroller.

2. Secondary storage.
Also known as axillary memory. This is just the opposite of primary storage. It basically
overcomes all the drawbacks of the primary storage area.

BIT,B‘lore 11
BPOPS103 Principles of Programming Using C

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.

 Processing.
 The process of performing operation on the data as per the instructions specified by the user is
called processing.
 Data and instructions are taken from primary memory and transfer to the arithmetic and logic
unit, which performs all sorts of calculations.
 The intermediate results of processing may be stored in main memory as they may be required
again.
 When processing completes, the final result is then transfered to the main memory. Hence the
data may move from main memory to ALU multiple times before the processing is over.

 Output.
 Output is the processing of the giving the result of data processing to the outside world.
 The results are given through output devices such as monitor, Printer, Etc.
 The output devices Therefore convert the result available in binary code into a human readable
language before displaying it to the user.

1. Control unit.
The control unit is the central nervous system of the entire computer system. It manages and controls
all the components of the computer system.

BIT,B‘lore 12
BPOPS103 Principles of Programming Using C

DESIGNING EFFICIENT PROGRAMS


Programming Paradigms:
A programming paradigm is a fundamental style of programming that defines how the structure and
basic elements of a computer program will be built.
It can be classified as follows:
 Monolithic programming: Emphasis finding a solution
 Procedural programming: lays stress on algorithms
 Structured programming: focuses on modules
 Object-oriented programming: emphasizes on classes and objects
 Logic-oriented programming: focuses on goals usually expressed in predicate calculus
 Rule-oriented programming: makes use of ‗if-then-else‘ rules for computation
 Constraint-oriented programming: utilizes invariant relationships to solve a problem.

1Monolithic Programming:

 Assembly language and BASIC are the monolithic


programming language.
 Monolithic programs have just one program module as such
programming languages do not support the concept of subroutines.
Therefore, all the actions required to complete a particular task are
embedded within the same application itself. This not only makes the
size of the program large but also makes it difficult to debug and
maintain.
 It consists global data and followed by sequential code.
 The global data can be accessed and modified from any part
of the program.
 A sequential code is one in which all instructions are executed in the specified sequence. In order
to change the sequence of instructions, jump statements or ‗goto‘ statements are used.
2. Procedural Programming
 In procedural languages, a program is divided into
subroutines that can access global data.
 To avoid repetition of code, each subroutine performs a
well-defined task. A subroutine that needs the service
provided by another subroutine can call that subroutine.
Therefore, with ‗jump‘, ‗goto‘, and ‗call‘ instructions, the
sequence of execution of instructions can be altered.
 FORTRAN and COBOL are two popular procedural
programming languages.

BIT,B‘lore 13
BPOPS103 Principles of Programming Using C

Advantages
 The only goal is to write correct programs
 Programs are easier to write as compared to monolithic programming
Disadvantages
 No concept of reusability
 Requires more time and effort to write programs
 Programs are difficult to maintain
 Global data is shared and therefore may get altered (mistakenly)
3. Structured Programming
 Structured programming employs a top-down
approach in which the overall program
structure is broken down into separate modules.
 This allows the code to be loaded into memory
more efficiently and also be reused in other
programs.
 Modules are coded separately and once a
module is written and tested individually, it is
then integrated with other modules to form the
overall program.
 Structured programming is based on modularization which groups related statements together
into modules.
Advantages
 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.
 Modules or procedures written for one program can be reused in other programs as well.
 Each module performs a specific task.
 Each module has its own local data.
 A structured program is easy to debug because each procedure is specialized to perform just
one task.
 Individual procedures are casy to change as well as understand.
 More emphasis is given on the code and the least importance is given to the data.
Disadvantages
 Not data-centred.
 Global data is shared and therefore may get inadvertently modified
 Main focus is on functions

BIT,B‘lore 14
BPOPS103 Principles of Programming Using C

4. Object-Oriented Programming (OOP)


 The object-oriented paradigm is task-based and data-based. In
this paradigm, all the relevant data and tasks are grouped
together in entities known as objects.
 It treats data as a critical element in the program development
and restricts its flow freely around the system.
 The striking features of OOP include the following:
o Programs are data centred.
o Programs are divided in terms of objects and not procedures.
o Functions that operate on data are tied together with the data.
o Data is hidden and not accessible by external functions.
o New data and functions can be easily added as and when
required.
o Follows a bottom-up approach for problem solving.

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 known as software development life cycle(SDLC).
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. The output of one phase provides the input for
its subsequent phase.
The figure 1.12 shows the phases of SDLC.
1. Requirement Analysis: The functionality,
capability, performance, availability of hardware and
software components are all analyzed in this phase. 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 or the
objective of the overall software product. The last activity in
this phase includes documenting every identified requirement
of the users in order to avoid any doubts or uncertainty
regarding the functionality of the programs.
2. Design: The design phase, specifies how the
program/software will be built. 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. Design phase the core
structure of the software/program is broken down into modules. The solution of the program is then
specified for each module in the form of algorithms, flowcharts, or pseudocodes.

BIT,B‘lore 15
BPOPS103 Principles of Programming Using C

3. Implementation: In this phase, the designed algorithms are converted into program code using
any of the high level languages. 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 software is compatible with the available hardware and other software
components that were mentioned in the Requirements Specification Document created in the first
phase.
4. Testing: In this phase, all the modules are tested together to ensure that the overall system works
well as a whole product. 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.
5. 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. as a part of the deployment phase, it is very crucial to have training classes for the
users of the software.
6. 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.

Program Design Tools: Algorithms, Flowcharts, Pseudocodes:


1. Algorithms:
 The algorithm gives the logic of the program, that is, a step-by-step description of how to arrive
at a solution.
 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 the algorithm has been defined one
can implement it in any high-level language.
 An algorithm should have the following characteristics:
1. Be precise
2. Be unambiguous
3. Not even a single instruction must be repeated infinitely
4. After the algorithm gets terminated, the desired result must be obtained.

 Control Structures Used In Algorithms: An algorithm can employ any of the three control
structures, namely, sequence, decision, and repetition
a) 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.

BIT,B‘lore 16
BPOPS103 Principles of Programming Using C

b) 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‖. A condition in this context is any
statement that may evaluate either to a true value or a false value.

c) 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. Below is an algorithm that prints the
first 10 natural numbers.

Examples:
1. Write an algorithm for interchanging/swapping two values.
Step 1: Input first number as A
Step 2: Input second number as B
Step 3: Set temp = A
Step 4: Set A=B
Step 5: Set B = temp
Step 6: Print A, B
Step 7: End

2. Write an algorithm to find the larger of two numbers.


Step 1: Input the first number as A.

BIT,B‘lore 17
BPOPS103 Principles of Programming Using C

Step 2: Input the second number as B.


Step 3: If A > B
Print A is greater.
Else-If
Print B is greater.
Else
Print both are equal.
[End of If]
Step 4: End

2. Flowchart:
 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.
 When designing a flowchart, each step in the process is depicted by a different symbol and is
associated with a short description.
 The symbols in the flowchart are linked together with arrows to show the flow of logic in the
process.
 The symbols of a flowchart include:
Name Symbol Usage
Start and end Represented as circles, ovals, or rounded rectangles.
symbol / Terminal Terminal symbols are always the first and the last
symbol 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 Called as an activity, is represented using a
processing step 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 Represented using a parallelogram and are used to
Symbol get inputs from the users or display the results to
them.
Condition/ Represented using a diamond. It is basically used to
Decision symbol 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

BIT,B‘lore 18
BPOPS103 Principles of Programming Using C

than two arrows, which indicate that a complex


decision is being taken.

Labelled Represented by an identifying label inside a circle


connectors and are used in complex or multi sheet diagrams to
substitute for arrows. For each label, the ‗outflow‘
connector must have one or more ‗inflow‘
page Off-page connectors. A pair of identically labelled connectors
connector connector issued to indicate a continued flow when the use of
lines becomes confusing.
Subroutine Indicates pre-defined process such as subroutines or
modules.

Comment Used to add comment or clarification.

Significance of flowchart:
 A flowchart is a diagrammatic representation that illustrates the sequence of steps that must be
performed to solve a problem.
 It facilitates communication between programmers and users.
 Once a flowchart is drawn, it becomes easy for the programmers to write the program in any
high-level language.
 A flowchart follows the top-down approach in solving problems.
Advantages:
 They are very good communication tools to explain the logic of a system to all concerned. They
help to analyze the problem in a more effective manner.
 They are also used for program documentation. They are even more helpful in the case of
complex programs.
 They act as a guide or blueprint for the programmers to code the solution in any programming
language. They direct the programmers to go from the starting point of the program to the ending
point without missing any step in between. This results in error-free programs.
 They can be used to debug programs that have error(s). They help the programmers to easily
detect, locate, and remove mistakes in the program in a systematic manner.

Limitations:
 Drawing flowcharts is a laborious and a time-consuming activity. Just imagine the effort required
to draw a flowchart of a program having 50,000 statements in it!
 Many a times, the flowchart of a complex program becomes complex and clumsy
 At times, a little bit of alteration in the solution may require complete redrawing of the flowchart
 The essentials of what is done may get lost in the technical details of how it is done.

BIT,B‘lore 19
BPOPS103 Principles of Programming Using C

 There are no well-defined standards that limit the details that must be incorporated into a
flowchart

Example:
1) Draw a flowchart to calculate the sum of the 2) Draw a flowchart to add two numbers.
first 10 natural numbers.

3) Draw a flowchart to determine the largest of three numbers.

BIT,B‘lore 20
BPOPS103 Principles of Programming Using C

3. Pseudocodes:
 Pseudocode is a compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language
 An ideal pseudocode must be complete, describing the entire logic of the algorithm.
 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 4 program's algorithm.
 They should not include keywords in any specific computer language.
Example:
1) Write a pseudocode for calculating the price of a product after adding the 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 x; sales tax rate
4. Calculate total price = price of the product + sales tax
5. Print total price
6. End
Variables: price of the item, sales tax rate, sales tax, total price

2) Write a pseudocode to read the marks of 10 students. If marks is greater than 50, the student
passes, else the student fails. Count the number of students passing and failing.
Solution

BIT,B‘lore 21
BPOPS103 Principles of Programming Using C

1. Set pass to 0
2. Set fail to 0
3. Set no of students to 1
4. WHILE no of students <= 10
a. input the marks
b. IF marks >= SO then
Set pass = pass +1
ELSE Set fail = fail +1
ENDIF
ENDWHILE
5. Display pass
6. Display fail
7. End
Variables: pass, fail, no of students, marks.

Types of Errors:
 Errors if not removed will either give erroneous output or will not let the compiler to compile the
program.
 Errors are broadly classified under four groups namely - a) Runtime error, b) Linker error, c)
Compile-time error, d) Logical error.
a) Runtime error:
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 number
Run-time errors may terminate program execution, so the code must be written in such a way
that it handles all sorts of unexpected errors rather terminating it unexpectedly.
b) Compile-time error:
compile-time errors occur at the time of compilation of the program. Such errors can be further
classified as follows:
i. Syntax Errors: Syntax errors are generated when rules of a programming language are
violated.
ii. Semantic Errors: Semantic errors are those errors which may comply with rules of the
programming language but are not meaningful to the compiler.
c) Logical error:
 Logical errors are errors in the program code that result in unexpected and undesirable
output.
 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.

BIT,B‘lore 22
BPOPS103 Principles of Programming Using C

d) Linker Error:
These errors occur when the linker is not able to find the function definition for a given
prototype.

Testing And Debugging Approaches


Testing is an activity that is performed to verify correct behaviour of a program. It is specifically carried
out with an intent to find errors. In the implementation stage, the following three types of tests can be
conducted.
a) Unit testing: Unit testing is applied only on a single unit or module to ensure whether it exhibits
the expected behaviour.
b) Integration Testing: It is a logical extension of unit tests. In this test, two units that have already
been tested are combined into a component and the interface between them is tested. The guiding
principle is to test combinations of pieces and then gradually expanding the component to
include other modules as well until all the modules are tested together. Integration testing is done
to identify errors that occur when the units are combined.
c) System Testing: System testing checks the entire system.
Debugging is an activity that includes execution testing and code correction. The main aim of debugging
is locating errors and producing an error-free program code. Different approaches applied for debugging
a code includes:
a) 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.
b) 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.
c) Cause Elimination In this approach, a list of all possible causes of an error is developed. Then
relevant tests are carried out to eliminate each of them.

BIT,B‘lore 23
BPOPS103 Principles of Programming Using C

Introduction to C

BIT,B‘lore 24
BPOPS103 Principles of Programming Using C

Characteristics of C
C is a robust language with rich set of built-in functions and operators used to write complex programs.
The C compiler combines the features of assembly and high-level languages, which makes it best suited
for writing system software as well as business packages. Some basic characteristics of C language
 Cis a high-level programming language (programmer not worry about the machine code).
 Small size—C has only 32 keywords. This makes it relatively easy to learn.
 C makes extensive use of function calls.
 C is well suited for structured programming. C enables users to think of a problem in terms of
functions/modules. This feature facilitates ease in program debugging, testing, and maintenance.
 C supports loose typing (as a character can be treated as an integer and vice versa).
 Structured language as the code can be organized as a collection of one or more functions
 Stable language. ANSI C was created in 1983 and since then it has not been revised.
 Quick language Since C programs make use of operators and data types, they are fast and efficient.
 Facilitates low level (bitwise) programming.
 Supports pointers to refer computer memory, arrays, structures, and functions.
 Core language many other programming language are based on C.
 C is a portable language, i.c., a C program written for one computer can be run on another computer
with little or no modification.
 C is an extensible language as it enables the user to add his own functions to the C library.

BIT,B‘lore 25
BPOPS103 Principles of Programming Using C

Uses of C
The uses of C language can be summarized as follows:
 C language is primarily used for system programming. The portability, efficiency, the ability to
access specific hardware addresses, and low runtime demand on system resources make it a good
choice for implementing operating systems and embedded system applications.
 C has been so widely accepted by professionals that compilers, libraries, and interpreters of other
programming languages are often written in C
 For portability and convenience reasons, C is sometimes used as an intermediate language for
implementation of other languages. Examples of compilers which use C this way are BitC, Gambit,
the Glasgow Haskell Compiler, Squeak, and Vala.
 Basically, C was designed as a programming language and was not meant to be used as a compiler
target language. Therefore, although C can be used as an intermediate language it is not an ideal
option. This led to the development of C-based intermediate languages such as C
 C is widely used to implement end-user applications.
Structure of a C Program:
C program is composed of processor command, global declarative section and one or more function
blocks.
The preprocessor directives are instructions that indicate how the
program has to be compiled. include is one the preprocessor command
through which the compiler include the needed information from the
specified header file to the particular code.
In Global variables or constants can be declared in the global
declaration part.
C program contains one or more functions. Functions are defined as a
group of statements that are executed together. Function can be either
system defined or user defined functions. All functions are divided into
two parts:
a) Local declaration section: Data will be
visible only within that function. Stated in other terms, the life-time of
the data will be only till the function ends.
b) Statement section: Contains the code
that manipulates the data to perform a specified task.

main() function is a system defined function from which the C program


execution begins. Every C program must include one main function,
where as user defined functions can be of any number which can be
included based on the tasks to be performed.

BIT,B‘lore 26
BPOPS103 Principles of Programming Using C

First program:
#include<stdio.h>
int main()
{
printf(―\n Welcome to the world of C‖);
return 0;
}
O/P: Welcome to the world of C.
 #include<stdio.h>: Preprocessor command starts with # symbol, which include header file or
standard I/O in the program.
Note: stdio.h – include i/p or o/p functions helps in reading data from keyboard and printing data on
the screen.
 int main(): indicates the starting point of the program, int is the return value of the program that
returns the integer value after the last statement of the program. {} the two curly brackets are used to
group all the related statements of the main function.
 printf() – function defined in the stdio.h file, used to print text on the screen. Message that has to be
displayed on the screen is enclosed within the double quotes within the brackets. Printf() also
supports the usage of the escape sequences.
Escape Purpose Escape Purpose Escape Purpose
sequence sequence sequence
\a Audible Signal \n Newline \r Carriage return
\b Backspace \v Vertical tab \? Question mark
\t Tab \f New Page\ Clear \\ Back slash
screen
\‘ Single quote \O Octal constant \x Hexadecimal constant
 return 0 – return command is used to return the value 0 to the OS.
Note: Every statement in main function ends with a semi-colon(;).
Steps for execution:
 Save the program with ―.c‖ extension.
 Compile the code: ―tc filename.c‖- in Windows or ―cc filename.c‖- in Unix/Linux system.
Note: a.out will be the O/P file when compiled, To generate output file of your own name then
used -o command ex: ―cc filename.c -o filename‖- generates first as the output file.
 To get the o/p use ―./a.out‖ if the own file has been generated the used ―./filename‖.

Files Used in C Program:


Every C program has four file associated with it: 1) Source File, 2) Header File, 3) Object File, 4)
Executable File.
1) Source Code File: Contains the source code of the program. The file extension of any C source
code file is ―.c‖. This file contains C source code that defines the main function and maybe other
functions.
2) Header File: Header file have the extension ―.h‖. Subroutines of one program can be included in
the other with the help of the header file i.e., program containing the subroutine can be compiled
and the generated o/p file can be included as the header file.

BIT,B‘lore 27
BPOPS103 Principles of Programming Using C

Note: If the subroutine has been changed then the program has to be recompiled to include the
changed in the current working program.
Standard Header file are:
o string.h – for string handling functions.
o stdlib.h – for some miscellaneous functions.
o stdio.h – for standard input and output function.
o math.h – for mathematical function.
o alloc.h – for dynamic memory allocation.
o conio.h – for clearing the screen.
3) Object File: Object files are generated by the compiler as a result of processing the source code
file. Object files contain compact binary code of the function definitions. Linker uses these
object files to produce an executable file (.exe file) by combining the object files together. Object
files have a *.o‖ extension, Windows and MS-DOS have a ‗.obj‘ extension for the object file.
4) Binary Executable File: The binary executable file is generated by the linker. The linker links
the various object files to produce a binary file that can be directly executed. On Windows
operating system, the executable files have a ‗.exe‘ extension.

Compiling and Executing C Programs:

 C is a compiled language, a written C program is compiled through a C compiler that can create an
executable file. C program is human-readable, the executable file is a machine-readable file.
 In C language programs, there are two kinds of source files, the main (.c) source file, and header (.h)
source files.
 The compilation process shown in Figure 9.6 is done in two steps, In the first step, the preprocessor
program reads the source file as text, and produces another text file as output.
 The output of the preprocessor is a text file which does not contain any preprocessor statements. This
file is ready to be processed by the compiler.

BIT,B‘lore 28
BPOPS103 Principles of Programming Using C

 The compiler translates the source code into an object code. The object code contains the machine
instructions for the CPU, and calls to the operating system API.
 the object file is not an executable file. Therefore, in the next step, the object file is processed with
another special program called a linker.
 The linker combines the object file with library routines (supplied with the compiler) 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, These object files are combined
by the linker to produce an executable file.

Using of Comments:
It is a good programming practice to place some comments in the code to help the reader understand the
code clearly. C supports two types of comments.
 ‗//‘ is used to comment a single statement. This is known as a line comment. End of the line
specifies the end of the comment line.
 ‗/*‘ multiline commnent, a ‗/*‘ is ended with ‗*/‘, all the statement b/w these symbol are
comments. This is also known as block comment.

C Tokens:
Tokens are the basic building blocks in C language. A program is constructed using a combination of
these tokens, There are six main types of tokens in C.

Token in C

Keyword Variables Constants Strings Special Characters Operators


s
Characters in C:
Computer languages also use a character set that defines the fundamental units used to represent
information. The character set of C are:
 English alphabet: Include both lower case (a - z) as well as upper case (A - 2) letters.
 Digits: Include numerical digits from 0 to 9
 Special characters: Include symbols such as ~, @, #, $, %, ^, &, *, (, ), _, -, +, =, ;, ―, ‗, |, {, }, [, ], \,
/, ?, <, >,., !.
 White space characters: These characters are used to print a blank space on the screen.
 Escape sequence:
Escape Purpose Escape Purpose Escape Purpose
sequence sequence sequence
\a Audible Signal \n Newline \r Carriage return
\b Backspace \v Vertical tab \? Question mark
\t Tab \f New Page\ Clear screen \\ Back slash

BIT,B‘lore 29
BPOPS103 Principles of Programming Using C

\‘ Single quote \O Octal constant \x Hexadecimal constant


\‖ Double quote \f Form feed \r Carriage return

Keywords:
 C has a set of reserved words often known as keywords.
 All keywords are basically a sequence of characters that have a fixed meaning.
 All keywords must be written in lowercase (small) letters.
 C language has 32 keywords as listed below.

Identifiers:
 Identifiers, help us to identify data and other objects in the program.
 Identifiers are basically the names given to program elements such as variables, arrays, and
functions.
 Identifiers may consist of sequence of letters, numerals, or underscores.

The rules to write an identifier are as follows:


1. It must contain only alphabets (A to Z, a to z), numbers (0 to 9) and underscore ( _ ).
2. It must start with alphabet or underscore but not numeric character.
3. It should not contain any special symbols apart from underscore.
4. It should not have any space.
5. Keywords cannot be used as identifiers.
6. Identifiers are case sensitive.
7. Maximum length of an identifier is 31 characters.
 Examples of valid identifiers include: roll_number, marks, name, emp_number, HRA, DA,
dept_code, DeptCode, RollNo, EMP_NO
 Examples of invalid identifiers include: 23_student, Xmarks, @name, #emp_number, basic.pay, -
HRA, (DA), &dept_code, auto

BIT,B‘lore 30
BPOPS103 Principles of Programming Using C

Basic Datatypes in C:

C language has very few basic datatypes as shown in below table.

The signed and unsigned datatypes in C is shown in below table.

BIT,B‘lore 31
BPOPS103 Principles of Programming Using C

void type holds no value. It is primarily used in three cases:


 To specify the retum type of a function (when the function returns no value).
 To specify the parameters of the function (when the function accepts no arguments from the
caller)
 To create generic pointers, We will read about generic pointers in the chapter on Pointers.
Variables:
A variable is defined as a meaningful name given to a data storage location in computer memory.
Variable actually refer to address of the memory where the data is stored.
C language supports two basic kinds of variables—numeric and character.
a) Numeric Variables: Numeric variables can be used to store cither integer values or floating
point values. It can also be associated with modifiers like short, long, signed, unsigned.
b) Character Variables: Character variables are just single characters enclosed within single
quotes, These characters could be any character from the ASCII character set—letters (‗a‘, ‗A‘),
numerals (‗2‘), or special characters (‗&‘).
Declaration of variables:
 Each variable to be used in the program must be declared.
 To declare a variable, specify the data type (specifies what kind of value a variable will store) of the
variable followed by its name.
 In C, variable declaration always ends with a semicolon, for example:
int emp_num;
float salary;

BIT,B‘lore 32
BPOPS103 Principles of Programming Using C

char grade;
double balance_amount;
unsigned short int acc_no;
Initialization of variables:
 While declaring variables, we can also initialize them with some value. For example,
int emp_num = 7;
float salary = 2156.35;
char grade = ‗A‘;
double balance_amount = 100000000;
 The initializer applies only to the variable defined immediately before it, Therefore, the statement
“int count, flag = 1;” initializes the variable flag and not count.
 When variables are declared but not initialized they usually contain garbage values.

Constants:
 Constants are identifiers whose values do not change. A constant is an explicit data value specified
by the programmer. Compiler knows the value of constant at compile time.
 Constants are used to define the values that shouldn‘t be changed throughout the program even by
mistake.

a) Integer Constant: A constant of integer type consists of a sequence of digits.


For example: 1, 34, 567, 8907 are valid integer constants.
 A literal integer like 1234 is of type int by default.
 For a Long integer constant the literal is succeeded with either ‗L‘ or ‗l‘ (like 1234567L).
 Similarly, an unsigned int literal is written with a ‗U‘ or ‗u‘ suffix (e.g. 12U).
1234L, 12341, 1234U, 1234u, 1234LU, 1234u) are all valid integer constants.
 Integer literals can be expressed in decimal, octal, or hexadecimal notation.
 By default an integer is expressed in decimal notation, Decimal integers consist of a
set of digits, 0 through 9, preceded by an optional - or + sign.
Examples of decimal integer constants include: 123, -123, +123, and 0.
 An integer constant preceded by a zero (0) is an octal number, Octal integers consist
of a set of digits, 0 through 7.
Examples of octal integers: 012, 0, 01234.
 integer constant is expressed in hexadecimal notation if it is preceded with 0x or 0x.
Hexadecimal numbers contain digits from 0-9 and letters A through F, which
represent numbers 10 through 15.

BIT,B‘lore 33
BPOPS103 Principles of Programming Using C

Examples of hexadecimal integers are 0X12, 0x7F, 0xABCD, 0X1A38.


Note: While writing integer constants, embedded spaces, commas, and non-digit characters are
not allowed. Therefore, integer constants given below are totally invalid in C
123 456
12,34,567
$123
b) Real/Floating Point Constants: A floating point constant consists of an integer part, a decimal
part, a fractional part, and an exponent field containing an e or E (e means exponent) followed by
an integer.
Examples of floating point numbers are: 0,02, -0.23, 123.456, +0.34 123, 0.9, -0.7, 40.8 etc.
 A literal like 0.07 is treated as of type double by default To make it a float type literal,
you must specify it using suffix F or f (Note that suffix L is for long double.)
Some valid floating point literals are: 0.02F, 0.34f, 3.141592654L, 0.002146, 2.14E-
3.
 A floating point number may also be expressed in terms of scientific notation.
Mantissa can be integer or floating point number and exponent is an integer with an
optional plus or minus sign.
Examples are: 0.5e2, 14E-2, 1.2e+3, 2.1E-3, -5.6e-2.
Note: scientific notation is used to express numbers that are either very small or very
large, For example: 120000000 = 1.2E8 and -0.000000025 = -2,.5E-8
c) Character Constants: A character constant consists of a single character enclosed in single
quotes. For example, ‗a‘ and ‗@‘ are character constants. In computers, characters are stored
using machine's character set using ASCII (American Standard Code for Information
Interchange) codes.
Character Constants are of two types:
i. Printable characters: All characters are printable except backslash(\) character .
ii. Non-Printable Characters: The characters with backslash (\) are non printable
i.e., escape sequences

BIT,B‘lore 34
BPOPS103 Principles of Programming Using C

The above table shows the decimal and hexadecimal ASCII value of each character.
d) String Constants: A string constant is a sequence of characters enclosed in double quotes.
 When a string constant is encountered in a C program, the compiler records the address of
the first character and appends a null character (―\0‖) to the string to mark the end of the
string.
 Thus, length of a string constant is equal to number of characters in the string plus + (for the
null character), Therefore, the length of string literal "hello" is 6.
Example: ―HELLO‖
H E L L O \0
0 1 2 3 4 5
Declaring Constants: To declare a constant, precede the normal variable declaration with const
keyword and assign it a value.
For example, ―const float pi = 3.14;‖
Note: The const keyword specifies that the value of pi cannot change.

BIT,B‘lore 35
BPOPS103 Principles of Programming Using C

Another way to designate a constant is to use the pre-processor command define using ‗#‘.
Example: ―#define pi 3.14159‖
Example program:
#include<stdio.h>
#define PI 3.1416 // define constant
void main()
{
const float cpi=3.1416; //memory constant
printf(―literal constant:%f\n‖,3.1416); //literal constant
printf(― defined constant:%f\n‖,PI);
printf(―memory constant:%f\n‖cpi);
}
Output:
literal constant: 3.1416
defined constant: 3.1416
memory constant: 3.1416

Rules that need to be applied to a #define statement which defines a constant:


Rule 1: No blank spaces are permitted between the # symbol and define keyword.
Rule 2: Blank space must be used between define and constant name and between constant name and
constant value.
Rule 3: #define is a pre-processor compiler directive and not a statement. Therefore, it does not end
with a semi-colon.

Input/Output Statement in C:
Streams:
 A stream acts in two ways. It is the source of data as well as the destination of data.
 C programs input data and output data from a stream. Streams are associated with a physical device
such as the monitor or with a file stored on the secondary memory.
 In a text stream, sequence of characters is divided into lines with each line being terminated with a
newline character (\n). On the other hand, a binary stream contains data values using their memory
representation.
 Although, we can do input/output from the keyboard/monitor or from any file but in this chapter we
will assume that the source of data is the keyboard and destination of the data is the monitor.

BIT,B‘lore 36
BPOPS103 Principles of Programming Using C

 printf() [Output Statement]:


 The printf function (stands for print formatting) is used to display information required by
the user and also prints the values of the variables.
 The printf function takes data values, converts them to a text stream using formatting
specifications in the control string and passes the resulting text stream to the standard
output.
 The syntax of printf() is as given below:
printf ("control string", variable list);
Control String: C string that contains the text that has to be written on to the standard
output device. As part of control string printf() the function can have as many additional
arguments (known as format specifiers) as specified in the prototype.
The prototype of the control string can be given as follows.
%[flags][width][.precision][length modifier] type specifier
Note: Each control string must begin with a % sign, which specifies how the next
variable has be printed.
i. Flag: An optional argument which specifies output justification such as numerical
sign, trailing zeros or octal, decimal, or hexadecimal prefixes. Flags used in C
program

ii. Width: An optional argument which specifies the minimum number of positions
in the output. If data needs more space than specified, then printf overrides the
width specified by the user, and if the number of output characters is smaller than
the specified width, then the output would be right justified with blank spaces to
the left.
iii. Precision: An optional argument which specifies the maximum number of
characters to print.
Note: For floating point numbers, the precision flag specifies the number of
decimal places to be printed.
Format can be given as .m, where m specifies the number of decimal digits. When
no precision modifier is specified, printf prints six decimal positions.
When both width and precision fields are used, width must be large enough to
contain the integral value and the decimal point of a number.
Ex: %7.3f means print a floating point value of maximum 7 digits where 3 digits
are allotted for the digits after the decimal point.

BIT,B‘lore 37
BPOPS103 Principles of Programming Using C

iv. Length Modifiers:

v. Type specifiers: They are used to define the type and the interpretation of the
value of the corresponding argument.

BIT,B‘lore 38
BPOPS103 Principles of Programming Using C

BIT,B‘lore 39
BPOPS103 Principles of Programming Using C

BIT,B‘lore 40
BPOPS103 Principles of Programming Using C

Note: The minimum field width and precision specifiers are usually constants. However, they may
also be provided by arguments to printf(). This is done by using the * modifier as shown in the
printf statement below.
printf("%*.*#", 10, 4, 1234.34);
Here, the minimum field width is 10, the precision is 4, and the value to be displayed is 1234.34

Examples:
float a=98.765432;
printf(“\n %7.4f \n %7.2f \n %-7.2f \n %f \n %10.2e \n %11.4e \n %-10.2e \n %e”, a, a, a,
a, a, a, a, a);
Output:
98.7654
98.77
98.77
98.7654
9.88e+01
9.8765e+01
9.88e+01
9.876540e+0
char ch = „A‟;
printf(“\n %c \n %3c \n %5c", ch, ch, ch);
Output:
A
A
A
printf(“\n This is \‟so\‟ beautiful”);
O/P: This is ‗so‘ beautiful
printf(“\n a = |%-+7.2f| b = %07.2f c = %-0+8.2f", 1.2, 1.2, 1.2);
O/P: a= +1.20 b = 0001.20 c = 1.20

BIT,B‘lore 41
BPOPS103 Principles of Programming Using C

 scanf() [Input statement]:The scanf() function stands for scan formatting and is used to read
formatted data from the keyboard.
The scanf function takes a text stream from the keyboard, extracts and formats data from the stream
according to a format control string and then stores the data in specified program variables,
The syntax of the scanf() function can be given as:
scanf("control string", argl, arg2, arg3,……., argn);
Control string specifies the type and format of the data that has to be obtained from the keyboard
and stored in the memory locations pointed by arguments arg1, arg2,.., argn, i.e,, the arguments are
actually the variable addresses where each piece of data is to be stored.
The prototype of the control string can be given as:
%[*] [width] [modifier]type
Here * is an optional argument that suppresses assignment of the input field, ic., it indicates that data
should be read from the stream but ignored (not stored in memory location).
i. Width: an optional argument that specifies the maximum number of characters to be read.
ii. Modifier: An optional argument that can be h, 1, or L for the data pointed by the
corresponding additional arguments. Modifier h is used for short int or unsigned short int, l is
used for long int, unsigned long int, or double values, Finally, L is used for long double data
values.
iii. Type: Specifies the type of data that has to be read. It als6 indicates how this data is expected
to be read from the user.
Note: a) The scan function ignores any blank spaces, tabs, and newlines entered by the user.
b) The function simply returns the number of input fields successfully scanned and stored.
c) The address of the variable is denoted by an *&‘ sign followed by the name of the variable.
The rules to use a scanf function in C programs.
Rule 1: The scanf function works until
(a) the maximum number of characters has been processed,
(b) a white space character is encountered, or
(c) an error is detected.
Rule 2: Every variable that has to be processed must have a conversion specification associated with it.
Therefore, the following scanf statement will generate an error as num3 has no conversion specification
associated with it
scanf(“%d %d", &num1, &num2, &num3);
Rule 3: There must be a variable address for each conversion specification. Therefore, the following
scan statement will generate an error as no variable address is given for the third conversion
specification.
scanf("%d %d %d", &num1, &num2);
Rule 4: An error will be generated if the format string is ended with a white space character.
Rule 5: The data entered by the user must match the character specified in the control string (except
white space or a conversion specification), otherwise an error will be generated and scanf will stop its
processing.
Rule 6: Input data values must be separated by spaces.
Rule 7: Any unread data value will be considered as a part of the data input in the next call to scanf.

BIT,B‘lore 42
BPOPS103 Principles of Programming Using C

Rule 8: When the field width specifier is used, it should be large enough to contain the input data size.

Example-3:
Char ch;
scanf(%ch ", &ch); -> reads a single character

char str[10];
scanf("%s ", str); -> reads a string of length 10

The below table shows the scanf format codes commonly used:

BIT,B‘lore 43
BPOPS103 Principles of Programming Using C

Example:
The following code combines reading of variables of different data types in one single statement
int num;
float frum;
char ch;
char str[10];
scanf ("%d %f %e %s", &num, &fnum, &ch, str);
The statement ignores the character variable and does not store it (as it is preceded by *)
scanf("%d %f %*c %s", &num, &fnum, &ch, str);

Detecting error during data input:


 When the scanf function completes reading all the data values, it returns the number of values that
are successfully read.
 This return value can be used to determine whether there was any error while reading the input.
For example, the statement,
scanf("%d %f %c", &a, &b, &c); will return 3 if the user enters, say,
> 12 12.34 A
It will return 1 if the user enters erroneous data like
> 12 ABC 12.34
This is because a string was entered while the user was expecting a floating point value. So, the scanf
function reads only first data value correctly and then terminates as soon as it encounters a mismatch
between the type of data expected and the type of data entered.

BIT,B‘lore 44

You might also like