CCP 21CS111 (UNIT1) Updated
CCP 21CS111 (UNIT1) Updated
CCP 21CS111 (UNIT1) Updated
PROGRAMMING
Characters set, C tokens, Keywords and identifiers, Constants, Variables, Data Types,
and Declaration of Variables.
Today, almost all of us in the world make use of computers in one way or the other. It
finds applications in various fields of engineering, medicine, commercial, research and others.
Not only in these sophisticated areas, but also in our daily lives, computers have become
indispensable. They are present everywhere, in all the devices that we use daily like cars, games,
washing machines, microwaves etc. and in day to day computations like banking, reservations,
electronic mails, internet and many more.
The word computer is derived from the word compute. Compute means to calculate.
The computer was originally defined as a superfast calculator. It had the capacity to solve
complex arithmetic and scientific problems at very high speed. But nowadays in addition to
handling complex arithmetic computations, computers perform many other tasks like accepting,
sorting, selecting, moving, comparing various types of information. They also perform arithmetic
and logical operations on alphabetic, numeric and other types of information. This information
provided by the user to the computer is data.
The information in one form which is presented to the computer is the input information
or input data. Information in another form is presented by the computer after performing a
process on it. This information is the output information or output data. The set of instructions
given to the computer to perform various operations is called as the computer program. The
process of converting the input data into the required output form with the help of the computer
program is called as data processing. The computers are therefore also referred to as data
processors. Therefore a computer can now be defined as a fast and accurate data processing
system that accepts data, performs various operations on the data, has the capability to store the
data and produce the results on the basis of detailed step by step instructions given to it.
The terms hardware and software are almost always used in connection with the
computer.
The Hardware:
The Software:
The computer hardware itself is not capable of doing anything on its own. It has to be given
explicit instructions to perform the specific task. The computer program is the one which
controls the processing activities of the computer. The computer thus functions according to
the instructions written in the program. Software mainly consists of these computer programs,
procedures and other documentation used in the operation of a computer system. Software is
a collection of programs which utilize and enhance the capability of the hardware.
Functionalities of a Computer
There are three basic functionalities of a Computer System and they are
1. Input
2. Process
3. Output
But if we look at it in a very broad sense, any digital computer carries out the following five
functions:
Step 1 - Takes data as input.
Step 2 - Stores the data/instructions in its memory and uses them as required.
Step 3 - Processes the data and converts it into useful information.
Step 4 - Generates the output.
Step 5 - Controls all the above four steps.
Generations of Computers
First Generation
1
The period of first generation: 1946-1959. Vacuum tube based.
Second Generation
2
The period of second generation: 1959-1965. Transistor based.
Third Generation
3
The period of third generation: 1965-1971. Integrated Circuit based.
Fourth Generation
4
The period of fourth generation: 1971-1980. VLSI microprocessor based.
Fifth Generation
5
The period of fifth generation: 1980-onwards. ULSI microprocessor based.
7
First Generation Computers
The period of first generation was from 1946-1959. The computers of first generation used
vacuum tubes as the basic components for memory and circuitry for CPU (Central Processing
Unit). These tubes, like electric bulbs, produced a lot of heat and the installations used to fuse
frequently. Therefore, they were very expensive and only large organizations were able to
afford it.
In this generation, mainly batch processing operating system was used. Punch cards, paper
tape, and magnetic tape was used as input and output devices. The computers in this
generation used machine code as the programming language.
The main features of the first generation are:
• Vacuum tube technology
• Unreliable
• Supported machine language only
• Very costly
• Generates lot of heat
• Slow input and output devices
• Huge size
• Need of AC
• Non-portable
• Consumes lot of electricity
Some computers of this generation were:
• ENIAC
• EDVAC
• UNIVAC
• IBM-701
• IBM-750
8
Second Generation Computers
The period of second generation was from 1959-1965. In this generation, transistors were
used that were cheaper, consumed less power, more compact in size, more reliable and faster
than the first -generation machines made of vacuum tubes. In this generation, magnetic cores
were used as the primary memory and magnetic tape and magnetic disks as secondary storage
devices.
In this generation, assembly language and high-level programming languages like
FORTRAN, COBOL were used. The computers used batch processing and
multiprogramming operating system.
The main features of second generation are:
• Use of transistors
• Reliable in comparison to first generation computers
• Smaller size as compared to first generation computers
• Generates less heat as compared to first generation computers
• Consumed less electricity as compared to first generation computers
• Faster than first generation computers
• Still very costly
• AC required
• Supported machine and assembly languages
Some computers of this generation were:
• IBM 1620
• IBM 7094
• CDC 1604
• CDC 3600
• UNIVAC 1108
9
Third Generation Computers
The period of third generation was from 1965-1971. The computers of third generation used
Integrated Circuits (ICs) in place of transistors. A single IC has many transistors, resistors,
and capacitors along with the associated circuitry.
The IC was invented by Jack Kilby. This development made computers smaller in size,
reliable, and efficient. In this generation remote processing, time-sharing, multi-programming
operating system were used. High- level languages (FORTRAN-II TO IV, COBOL,
PASCAL PL/1, BASIC, ALGOL-68 etc.) were used during this generation.
The main features of third generation are:
• IC used
• More reliable in comparison to previous two generations
• Smaller size
• Generated less heat
• Faster
• Lesser maintenance
• Costly
• AC required
• Consumed lesser electricity
• Supported high-level language
Some computers of this generation were:
• IBM-360 series
• Honeywell-6000 series
• PDP (Personal Data Processor)
• IBM-370/168
• TDC-316
10
Fourth Generation Computers
The period of fourth generation was from 1971-1980. Computers of fourth generation used
Very Large Scale Integrated (VLSI) circuits. VLSI circuits having about 5000 transistors and
other circuit elements with their associated circuits on a single chip made it possible to have
microcomputers of fourth generation.
Fourth generation computers became more powerful, compact, reliable, and affordable. As a
result, it gave rise to Personal Computer (PC) revolution. In this generation, time sharing, real
time networks, distributed operating system were used. All the high-level languages like C,
C++, DBASE etc., were used in this generation.
The main features of fourth generation are:
• VLSI technology used
• Very cheap
• Portable and reliable
• Use of PCs
• Very small size
• Pipeline processing
• No AC required
• Concept of internet was introduced
• Great developments in the fields of networks
• Computers became easily available
Some computers of this generation were:
• DEC 10
• STAR 1000
• PDP 11
• CRAY-1(Super Computer)
• CRAY-X-MP(Super Computer)
11
The main features of fifth generation are:
• ULSI technology
• Development of true artificial intelligence
• Development of Natural language processing
• Advancement in Parallel Processing
• Advancement in Superconductor technology
• More user-friendly interfaces with multimedia features
• Availability of very powerful and compact computers at cheaper rates
Some computer types of this generation are:
• Desktop
• Laptop
• Notebook
• Ultrabook
• Chromebook
CLASSIFICATION OF COMPUTERS:
Computers are broadly classified into two categories depending upon the logic used in their
design as:
1. Analog computers:
In analog computers, data is recognized as a continuous measurement of a physical
property like voltage, speed, pressure etc. Readings on a dial or graphs are obtained as the
output, ex. Voltage, temperature; pressure can be measured in this way.
2. Digital Computers:
These are high speed electronic devices. These devices are programmable. They process
data by way of mathematical calculations, comparison, sorting etc. They accept input and
produce output as discrete signals representing high(on) or low (off) voltage state of
electricity. Numbers, alphabets, symbols are all represented as a series of 1s and Os.
Digital Computers are further classified as General Purpose, Digital Computers and
Special Purpose Digital Computers. General Purpose computer can be used for any
applications like accounts, payroll, data processing etc. Special purpose computers are
used for a specific job like those used in automobiles, microwaves etc.
Another classification of digital computers is done on the basis of their capacity to access
memory and size like:
Microcomputers: Microcomputers are generally referred to as Personal Computers
(PCs). They have smallest memory and less power. They are widely used in day to day
applications like office automation, and professional applications, ex. PCAT, Pentium
etc.
Note Book and Laptop Computers: These are portable in nature and are battery
operated. Storage devices like CDs, floppies etc. and output devices like printer scanners
can be connected to these computers. Notebook computers are smaller in physical size
than laptop computers. However, both have powerful processors, support graphics, and
can accept mouse driven input.
Hand Held Computers:
These types of computers are mainly used in applications like collection of field data.
They are even smaller than the note book computers.
Hybrid Computers: Hybrid Computers are a combination of Analog and Digital
computers. They combine the speed of analog computers and accuracy of digital
computers. They are mostly used in specialized applications where the input data is in an
analog form i.e. measurement. This is converted into digital form for further processing.
The computers accept data from sensors and produce output using conventional
input/output devices.
Mini Computers: Mini computers are more powerful than the micro computers. They
have higher memory capacity and more storage capacity with higher speeds. These
computers are mainly used in process control systems. They are mainly used in
applications like payrolls, financial accounting, Computer aided design etc. ex. VAX,
PDP-11.
Mainframe Computers: Main frame computers are very large computers which process
data at very high speeds of the order of several million instructions per second. They can
be linked into a network with smaller computers, micro computers and with each other.
They are typically used in large organizations, government departments etc. ex.
IBM4381, CDC.
Super Computers: A super computer is the fastest, most powerful and most expensive
computer which is used for complex tasks that require a lot of computational power.
Super computers have multiple processors which process multiple instructions at the
same time. This is known as parallel processing. These computers are widely used in
very advanced applications like weather forecasting, processing geological data etc. ex.
CRAY-2, NEC - 500, PARAM.
APPLICATIONS OF COMPUTERS:
Today computers find widespread applications in all activities of the modern world. Some of
the major application areas include:
2. Business:
Record keeping, budgets, reports, inventory, payroll, invoicing, accounts are all the areas
of business and industry where computers are used to a great extent. Database
management is one of the major areas where computers are used on a large scale. The
areas of application here include banking, airline reservations, etc. where large amounts
of data need to be updated, edited, sorted, and searched from large databases.
3. Medicine:
Computerized systems are now in widespread use in monitoring patient data like, pulse
rate, blood pressure etc. resulting in faster and accurate diagnosis. Modern day medical
equipment’s are highly computerized today. Computers are also widely used in medical
research.
4. Information:
This is the age of information. Television, Satellite communication, Internet, networks
are all based on computers.
5. Education:
The use of computers in education is increasing day by day. The students develop the
habit of thinking more logically and are able to formulate problem solving techniques.
CDs on a variety of subjects are available to impart education. Online training programs
for students are also becoming popular day by day. All the major encyclopedias,
dictionaries and books are now available in the digital form and therefore are easily
accessible to the student of today. Creativity in drawing, painting, designing, decoration,
music etc. can be well developed with computers.
6. Games and Entertainment:
Computer games are popular with children and adults alike. Computers are nowadays
also used in entertainment areas like movies, sports, advertising etc.
ADVANTAGES OF COMPUTERS:
1. Speed:
The speed of a computer is measured in terms of the number of instructions that it can
perform or execute in a second. The speeds of computers are measured in milli seconds
(10~3 sec), micro-seconds (10~6 sec), and nano-seconds (10~9sec). Computers are
superfast machines and can process millions of instructions per second. Smaller
computers can execute thousands of instructions per second, while the more complex
machines can execute millions of instructions per second.
2. Accuracy:
Computers are very accurate. They are capable of executing hundreds of instructions
without any errors. They do not make mistakes in their computations. They perform each
and every calculation with the same accuracy.
3. Efficiency
The efficiency of computers does not decrease with age. The computer scan perform
repeated tasks with the same efficiency any number of times without exhausting
thereselves. Even if they are instructed to execute millions of instructions, they are
capable of executing them all with the same speed and efficiency without exhaustion.
4. Storage Capability
Computers are capable of storing large amounts of data in their storage devices. These
dev ices occupy very less space and can store millions of characters in condensed forms.
These storage devices typically include floppy disks, tapes, hard disks, CDs etc, the data
stored on these devices can be retrieved and reused whenever it is required in future.
5. Versatility
Computers are very versatile. They are capable not only of performing complex
mathematical tasks of science and engineering, but also other non-numerical operations
fielding air-line reservation, electricity bills, data base management etc.
LIMITATIONS OF COMPUTERS:
Although the computers of today are highly intelligent and sophisticated they have their
own limitations. The computer cannot think on its own, since it does not have its own brain. It
can only do what is has been programmed to do. It can execute only those jobs that can be
expressed as a finite set of instructions to achieve a specific goal. Each of the steps has to be
clearly defined. The computers do not learn from previous experience nor can they arrive at a
conclusion without going through all the intermediate steps. However the impact of computers
on today’s society in phenomenal and they are today an important part of the society.
Any system is defined as a group of integrated parts which are designed to achieve a common
objective. Thus, a system is made up of more than one element or part, where each element
performs a specific function and where all the elements (parts) are logically related and are
controlled in such a way that the goal (purpose) of the system is achieved. Each of these units
performs a specific task. However, none of them can function independently on their own. They
are logically related and controlled to achieve a specific goal. When they are thus integrated they
form a fully-fledged computer system.
Hardware Overview
The Motherboard is the main circuit board for the computer, containing both soldered,
nonremovable components along with sockets or slots for components that can be
removed. The motherboard holds the CPU, RAM and ROM chips, etc.
The Central Processing Unit (CPU) is the "brain" of the computer. It executes
instructions (from software) and tells other components what to do.
o The Intel Pentium is a popular processor for IBM-PCs.
o The PowerPC is a popular processor for Macintoshes.
o There are 2 parts of the CPU: The ALU and Control Unit.
o The Arithmetic Logic Unit (ALU) performs arithmetic operations (such as
addition and subtraction) and logical operations (such as comparing two values).
o An optional math co-processor can take the place of the ALU. It performs the
same operations, only it is faster.
o The Control Unit deciphers and carries out instructions.
o Different CPUs have different types of instructions, so software made for one
type of CPU will not run on other kinds.
o The word size denotes how many bits of data a CPU can process at once. 32 bits
is the standard word size for CPU's used in personal computers today. The higher
the word size, the faster a CPU can execute instructions.
The System Clock is an "electrical pulse generator" that sends out a pulse of electricity at
regular intervals. The electronic components of the computer need these electric pulses in
order to perform work. The more pulses sent out by the system clock, the faster the
computer. The first personal computers had clock speeds of 8 MHz (8 million pulses per
second); today's PC's have clock speeds greater than 3.2 GHz (3.2 billion pulses per
second).
Bus Lines are "electrical data roadways" (i.e. wires) through which bits of information
are transmitted between the CPU and other components. The bus size denotes how many
bits can be transmitted at once. In general, this should be the same as the CPU word size.
Memory Chips
o Random Access Memory (RAM), also known as Main Memory or Primary
Storage, is used to hold instructions and data while they are being used. RAM is
volatile, meaning its contents are lost when the power goes off. RAM is more than
1000x faster than the fastest secondary storage (see below).
o Cache memory is special high-speed memory that temporarily stores instructions
and data the CPU is likely to use frequently. This speeds up processing. Level 2
or external caches generally range in size from 64 Kilobytes to 2 Megabytes.
o Read Only Memory (ROM) chips are non-volatile memory that generally
contains instructions for "booting" the computer (i.e. loading the operating system
when the computer starts up).
o CMOS chips are powered by a battery and contain so-called "flexible
information" such as the type of hard drive your computer is using and the current
date and time.
o Flash chips do not require electricity or a battery yet are non-volatile. They are
used in computers, cell phones, digital cameras, etc.
Expansion Slots are sockets on the motherboard that you can plug expansion cards into.
To plug a card into a slot, you must open the system unit. A card contain a socket on its
end that sticks out from the system unit so a cable can be plugged into it. Common types
of cards are graphics, sound, and network cards.
Ports are sockets that are on the outside othe system unit, meaning you can easily plug a
cable into a port without opening the system unit.
o Serial ports transmit one bit of data at a time.
o Parallel ports transmit 8 bits of data at a time.
o Universal Serial Bus (USB) ports are much faster than serial or parallel ports and
allow multiple devices to be connected to the same port.
Secondary Storage
Devices that "permanently" hold data and information (i.e. programs).
Non-volatile memory; when the power goes off, contents are still saved (unless there is
an error).
Used to store instructions and data while they are not being used.
A floppy disk is a removable (i.e. portable) platter made of mylar plastic that is
magnetized. Bits of information are stored in concentric rings called tracks on either side
of the platter. The current floppy disk standard is a 3 1/2" platter in a hard plastic case
that holds 1.44 Megabytes of information. A Zip disk, on the other hand, can hold up to
250 Megabytes.
A hard disk is similar to a floppy disk but uses metal platters to store information. Hard
disks are not only much faster than floppy disks but can hold huge amounts of data
(hundreds of gigabytes).
Both floppy and hard drives use a read/write head, which is basically a magnet, to
read/write information from/to tracks on a platter. In a hard drive, the read/write head and
platter(s) are enclosed together in an air-tight package, making hard drives less
susceptible to damage. The read/write head hovers above the platter but should not touch
it. If touched, the platter can be damaged, resulting in the loss of some or all the data on
the platter. This is known as a head crash.
Magnetic tape is used mostly for backups. These are very slow because you have to fast
forward or rewind to the right spot. However, they are very reliable.
Optical discs use optical technology (i.e. lasers) instead of magnetic technology to store
information.
o CD-ROM stands for Compact Disc - Read Only Memory.
o CD-R stands for Compact Disc - Recordable and can be written to only once.
(Also known as CD-WORM: Compact Disc - Write Once, Read Many.)
o CD-RW stands for Compact Disc - Re-writeable (or Read/Write).
o DVD-ROM stands for Digital Versatile Disc - Read Only Memory.
o DVD-R stands for Digital Versatile Disc - Recordable and can be written to only
once.
(Also known as DVD-WORM: Digital Versatile Disc - Write Once, Read Many.)
o DVD-RW stands for Digital Versatile Disc - Re-writeable (or Read/Write).
o CD's can hold approximately 650 Megabytes of data while DVD's can hold up to
17 Gigabytes.
Input devices translate data into a form the computer can understand.
o The keyboard is the most common input device, but this type of data entry is
very slow and error-prone.
o Direct input devices are much faster and less error-prone.
Pointing devices such as the mouse, trackball, and touchpad allow you to
manipulate a cursor on the screen.
Scanning devices read data directly. For example, OMR (Optical Mark
Recognition) devices (such as a scantron machine) can sense marks on
paper. Even more advanced are OCR (Optical Characgter Recognition)
devices, which attempt to read letters. Bar Code Readers are often used in
grocery stores (i.e. with the UPC - Universal Product Code system) to scan
items.
Output devices translate information into a form humans can understand.
o The Monitor (or Display Screen) is the most common type of output device. It
produces softcopy (i.e. temporary) output on a screen.
o The Printer is the most second most common type of output device. It
produces hardcopy (i.e. "permanent") output on paper.
A Laser Printer uses a photoelectric drum and powdered ink, similar to a
copying machine, to produce output.
An Inkjet Printer produces output by spraying droplets of liquid ink onto
the paper from small nozzles. It is the most common type of printer in use
today and is generally very inexpensive.
Communications Devices
5. VGA Port:
VGA ports also known as Video Graphic Array connector are those which connect the monitor
to a computer’s video card. VGA port has 15 holes and it is similar to the serial port connector.
But VGA Ports have holes in it and the serial port connector has pins in it.
6. Sockets:
Microphones and speakers are connected with the help of Sockets to the sound card of the
computer.
7. FireWire Port:
The IEEE 1394 interface, which is developed in the late 1980s and early 1990s by Apple as
FireWire. It can transfer large amount of data at very high speed. It is used to connect
camcorders and video equipment to the computer. It comes up with three variants which are 4-
Pin FireWire 400 connector, 6-Pin FireWire 400 connector, and 9-Pin FireWire 800 connector.
8. Infrared Port:
An Infrared(IR) port is used to sends and receives infrared signals from other devices. It is a kind
of wireless type port with a limited range of 5-10ft.
9. Game Port:
These ports are used previously to connect a joystick to a PC. But nowadays it is replaced by
USB ports.
10. Modem Port:
As the name suggests, a Modem port is used to connects a PC’s modem to the telephone
network.
A problem can be solved successfully only after making an effort to understand the problem.
To understand the problem, the following questions help:
1. What do we know about the problem?
2. What is the information that we have to process in order the find the solution?
3. What does the solution look like?
4. What sort of special cases exist?
5. How can we recognize that we have found the solution?
It is important to see if there are any similarities between the current problem and other problems
that have already been solved. We have to be sure that the past experience does not hinder us in
developing new methodology or technique for solving a problem. The important aspect to be
considered in problem-solving is the ability to view a problem from a variety of angles.
It is important to see if there are any similarities between the current problem and other
problems that have already been solved. We have to be sure that the past experience does not
hinder us in developing new methodology or technique for solving a problem. The important
aspect to be considered in problem-solving is the ability to view a problem from a variety of
angles.
clear,
unambiguous,
step-by-step instructions.
No step, not even the most basic and elementary, can be left out.
When we design a program, we do not completely define the algorithms all at once. As we
develop the program and break down major components into smaller pieces, the algorithms for
each task become more complex and detailed.
Coding
Once you have designed a suitable program to solve a given problem, you must translate
that design into program code; that is, you must write statements (instructions) in a particular
programming language such as C++, Visual Basic, or JavaScript etc. to put the design into a
usable form.
Additional statements are included at this point to document the program. Documentation
is a way to provide additional explanation in plain English (or other mother tongue) that the
computer ignores but which makes it easier for others to understand the program code. Normally,
a programmer provides internal and external documentation. Internal documentation exists
within the code and explains it. External documentation is provided separate from the program in
a user’s guide or maintenance manual.
The ways that specific words and symbols are used by each language is called its syntax
(the rules that govern the structure of the language).
Documentation explains how the program works and how to use the program.
Documentation can be of great value, not only to those involved in maintaining or modifying a
program, but also to the programmers themselves. Details of particular programs, or particular
pieces of programs, are easily forgotten or confused without suitable documentation.
Documentation comes in two forms:
External documentation, which includes things such as reference manuals, algorithm
descriptions, flowcharts, and project workbooks
Internal documentation, which is part of the source code itself (essentially, the
declarations, statements, and comments)
Testing is the process of executing a program with the deliberate intent of finding errors.
Testing is needed to check whether the expected output matches the actual output. Program
should be tested with all possible input data and control conditions. Testing is done during every
phase of program development. Initially, requirements can be tested for its correctness. Then, the
design (algorithm, flow charts) can be tested for its exactness and efficiency.
Debugging is a process of correcting the errors. Programs may have logical errors which
cannot be caught during compilation. Debugging is the process of identifying their root causes.
One of the ways to ensure the correctness of the program is by printing out the intermediate
results at strategic points of computation.
Some programmers use the terms “testing” and “debugging” interchangeably, but careful
programmers distinguish between the two activities. Testing means detecting errors. Debugging
Dept. of CSE, NMAMIT Page 12
means diagnosing and correcting the root causes. On some projects, debugging occupies as much
as 50 percent of the total development time. For many programmers, debugging is the hardest
part of programming because of improper documentation.
Maintenance
A programming language can be defined as a vocabulary and set of grammatical rules for
instructing the computer to perform specific tasks. Each programming language has a unique set
of characters, keywords and the syntax for organizing programming instructions.
The term programming languages usually refers to high-level languages, such as BASIC, C,
C++,COBOL, FORTRAN, Ada, and Pascal.
Advantage
#The program runs faster because no translation is needed. (It is already in machine
understandable form)
Disadvantages
# It is very difficult to write programs in machine language. The programmer has to know
details of hardware to write program
# It is difficult to debug the program
Dept. of CSE, NMAMIT Page 14
(b) Assembly Language
In assembly language, set of mnemonics (symbolic keywords) are used to represent machine
codes. Mnemonics are usually combination of words like ADD, SUB and LOAD etc. In order to
execute the programs written in assembly language, a translator program is required to translate
it to the machine language. This translator program is called Assembler. Assembly language is
considered to be the second-generation language.
Advantages:
# The symbolic keywords are easier to code and saves time and effort
# It is easier to correct errors and modify programming instructions
# Assembly Language has utmost the same efficiency of execution as the machine level
language, because there is one-to-one translation between assembly language program and its
corresponding machine language program
Disadvantages:
#Assembly languages are machine dependent. A program written for one
computer might not run in other computer.
For example, COBOL (Common Business Oriented Language) is mostly suitable for business
Oriented applications. There are some numerical & mathematical oriented languages like
FORTRAN (Formula Translation) and BASIC (Beginners All-purpose Symbolic Instruction
Code).
Numerical Languages
Early computer technology dates from the era just before World War 2 in the late 1930s to the
early 1940s. These early machines were designed to solve numerical problems and were
thought of as ELECTRONIC CALCULATORS. Numerical calculations were the dominant
form of application for these early machines.
Business Languages
Business data processing was an early application domain developed after numerical
applications. In 1959, the US department of Defence sponsored a meeting to develop COMMON
BUSINESSLANGUAGE (CBL), which would be a business-oriented language that used English
as much as possible for its notation. This, in turn, led to the formation of a Short Range
Committee to develop COBOL.
Systems Languages
Because of the need of efficiency, the use of assembly language held on for years in the system
area long after other application domains started to use higher-level languages. Many systems
programming languages such as CPL & BCPL were designed, though not widely used. The
major landmark here is the development of UNIX, where high level languages also proceed to
work effectively.
Following are the most important features that would make a programming language efficient
andeasy to use:
Clarity, Simplicity and Unity: A programming Language provides, both a conceptual frame
work for thinking about algorithms and a means for expressing these algorithms. The syntax of a
language should be such that programs may be written, tested and maintained with ease.
Orthogonality: This refers to the attribute of being able to combine various features of a
language in all possible combinations, with every combination being meaningful. Orthogonality
makes a language easy to learn and write programs, because there are fewer exceptions & special
cases to remember.
Naturalness for the application: A language needs syntax that when properly used allows the
program structure to reflect the underlying logical structure of the algorithm. The language
should provide appropriate data structures, operations, control structures and natural syntax for
the problem to be solved.
Support for abstraction: Even with the most natural programming language for an application,
there is always a substantial gap remaining between the abstract data structures & operations that
characterize the solution to a problem and the particular data structures and operations built into
a language.
Cost of Program Maintenance: The highest cost involved in any program is the total life-
cycle costs including development costs & the cost of maintenance of the program while it is in
production use.
ALGORITHM
Algorithm is a step – by – step procedure which is helpful in solving a problem. If, it is written
in English like sentences then, it is called as ‘PSEUDO CODE’.
PROPERTIES OF AN ALGORITHM
Input
Output
Finiteness
Definiteness
Effectiveness
Example
Start
Read 3 numbers a,b,c
Compute sum = a+b+c
Compute average = sum/3
Print average value
Stop
FLOW CHART
Terminal start/stop/begin/end
Oval
Parallelogram
Rectangle
Diamon
Circle
Arrows
Hexagon
Example
Function 1
Function 2
USER DEFINED FUNCTIONS
Function n
Documentation Section:
Consists of a set of comment lines giving the name of the program, author, and other
details which the programmer would like to use later.
These are non executable lines i.e., compiler ignores these comment lines.
Example:
/* Computing and Printing Employee’s Salary Slip */
/* Prepared and compiled at NMAMIT, NITTE */
/* Prepared on April, 2021 */
Link Section:
It provides instruction to the compiler to link functions from the system library.
Example : #include <stdio.h>
#include <math.h>
Note: Link Section and User Definition Section are together called as the ‘PREPROCESSOR
STATEMENTS’ OR ‘PREPROCESSOR DIRECTIVES’
main( ) Function:
Every ‘C’ program must have only one main( ) function.
Execution of ‘C’ program starts from the main( ) function.
It should be written in lower case letters and should not be terminated by a semicolon.
It calls other library functions and user defined functions
Braces:
A pair of curly braces ‘{’ & ‘}’ are used in the main( ) function section.
The left brace {represents the beginning of execution of the main function and the right
brace} represents the end of execution of the main function.
These braces are also used to indicate the begining and end of user-defined functions and
compound statements.
Executable Part:
This part consists of statements which are instructions to computer to perform specific
operations.
They may be input-output statements, arithmetic statements, control statements and other
statements.
All such statements terminate with a semi colon.
/***********DOCUMENTATION SECTION*************/
/* PROGRAM TO COMPUTE AREA OF A
CIRCLE PREPARED BY XYZ
PREPARED ON 26-02-2006 */
/*************LINK SECTION*******************/
#include <stdio.h>
#include <conio.h>
C COMPILATION MODEL
Figure below illustrates the process of creating, compiling, and executing of C program, although
these steps remains the same irrespective of the operating systems( OS) commands for
implementing the steps and conventions for naming files may differ on different systems.
An OS is a program that controls the entire operation of computer system. All input/output
operations are channeled through the OS. The OS which is an interface between the hardware
and the user, handles the execution of user program.
Upper Case A to Z
Alphabets
Lower Case a to z
Digits 0 through 9
, Comma / Slash
. Period % Percentage
Special : Colon & Ampersand
Characters ; Semicolon ^ Caret
‘ Apostrophe (single quote) ~ Tilde
“ Double quote < Less than
‘C’ TOKENS
They are the smallest units or primitive elements of the grammar or syntax of ‘C’
language. Each and every line of a ‘C’ program will contain one or more ‘C’ tokens.
Identifiers:
They are names of variables representing data, labels, function names, array names, user-
defined names, user-defined objects, etc.
They are formed by sequences of alphabets and digits
Names of the identifiers once declared in C cannot be used to declare some other function
name or array name in a single program.
Number of significant characters to be recognized in an identifier varies from C compiler
to C compiler
Constants and Variables are two essential ingredients for Data Processing Applications
without which we may not be able to develop programs in any of the high level programming
languages.
CONSTANTS
These are fixed values that do not change during the execution of a program. They are also
known as literals.
Numeric Constants:
Non-Numeric Constant:
These comprise of both numerals and letters of alphabets including special symbols.
They are used in string manipulation applications like Natural Language Processing
(NPL)
Integer Constants:
Integer constants in ‘C’ represent whole numbers without any fractional part.
It is a sequence of digits without a decimal point.
It can be prefixed with a plus or minus sign.
When minus sign doesn’t precede the number, it is assumed to be a positive one.
There should not be any special symbols like blank spaces, comma, etc.
The general form of an integer constant is:
Sign Digits
where,
Sign optional plus sign for positive numbers and minus sign for negative numbers.
INTEGER CONSTANTS
VALID INVALID
2006 123902 +27 999 0.015oC 1,25,200 10 456
06 +2 0.027345+ 100.
Floating point constants are real numbers with a decimal point embedded in it.
Mantissa e Exponent
where,
Exponential notation is useful for representing numbers that are either very large
or very small in magnitude. Example: 3500000000 may be written as 3.5E9
&0.000000456 can be written as4.56E7
Character Constants:
A character constant in ‘C’ is a single character enclosed within a pair of single quotes.
Examples: ‘u’, ‘s’, ‘$’, ‘6’, ‘ ’, ‘?’, ‘!’, etc.
Each character constant in ‘C’ is identified with its ASCII integer value.
Character constants in ‘C’ are used mainly to represent some coding during data output.
String Constants:
A string constant in ‘C’ denotes a sequence of one or more characters enclosed within a
pair of double quotes.
Examples: “Hi” “y2k problem” “15th August” “2006”
“Welcome to C” “20% Loss”
A single character string doesn’t have an equivalent integer value, but a single character
constant has an integer value. Eg. “A” and ‘A’ are not the same.
‘C’ supports some special backlash character constants that are used in output function
printf to obtain special print effects.
It is a combination of two characters in which the first character is always a backlash ‘\’.
The second character can be any one of the characters a, b, f, n, t, v, ’, ”, \ and 0.
They are also known as ‘Escape Characters’ or ‘Escape Sequences’.
A list of the Backlash Constants used are listed in table below:
VARIABLES
A variable may be a data name that may be used to store data value.
They are used to identify different program elements, hence also known as ‘Identifiers’.
A variable may take different values at different times during execution of the program.
Each variable refers to specific memory locations in the Memory Unit where numerical
values or characters can be stored.
DATA TYPES IN C
The Four fundamental data types:
Examples of valid int data type: 2006 123902 +27 999 06 +2
o
Examples of invalid int data type: 0.0 15 C 1,25,200 10 456 0.027
345+ 100.
float is the key word used to denote a real number or floating point number (both in
fractional form and exponential form).
Floating point numbers are stored in 32 bits (4 bytes) with 6 digits of precision.
Examples: 1.5 0.563 123.0 27009.023 999.99
0.4876E12 235.46e102 +0.001E97
43.2e06 156E+05 1.234e07
double is the key word used to denote a double precision floating point number.
This is similar to float data type, only difference is that it is used to represent more
precision of the floating point number.
Double precision floating point numbers are stored in 64 bits (8 bytes) with 16 digits of
precision.
The storage size in bytes and range of values being represented by basic data types can be
modified with the help of the following modifiers or qualifiers as prefixes.
1. signed
2. unsigned
3. long
4. short
signed
This modifier can be applied to integer variables although default integer declaration
already assumes a signed number.
This modifier can be applied to both int and char data type variables.
However, char data type is unsigned by default and can hold integer values in the range
0 to 255.
An unsigned int data type can hold integer values in the range 0 to 65535
long
This modifier can be applied to both int and double data types.
When applied to int, it doubles the storage size from 2 bytes to 4 bytes.
long int can store integer values in the range2147483648 to +2147483647
A long integer can also be declared as long int or simply long.
When applied to double data type, the storage size increases from 8 bytes to 16 bytes.
Long double can store floating point number values in the range 3.4E4932 to
+1.1E+4932
short
DECLARATION OF VARIABLES
All the variables must be declared before they are used in a ‘C’ program
Declarations are necessary to indicate to the compiler the type of variable and to reserve
the amount of memory required to store the values held by them.
The syntax for declaring a variable is as follows:
data type Basic data type such as int, float, char, double, etc
Examples:
int count, i, j;
Variable_name = value ;
Where,
1. Assigning initial values to variables within the declaration section. This is called
initialization.
Example:int i, gd = 10, gm;
float m;
char name[50];
k = num;
m = 3.45;
Assignment
name = “MsBeautiful”;
Assignment Statements:
Variable_name = Expressio ;
Where, n
Variable_name represents the name of the variable where it must be stored.
Expression is
constant or a variable
function name or function call
array reference or structure reference
variables and/or constants coupled with operators
d = b * b 4 * a * c; y = num[8];
x-y = x + y;
(a * a – b)/2.6 = d * d – c * c;
125 = reg_no;
‘C’ has special short hand operators which will simplifies representation of certain assignment
statements.
Examples:
sum_of_digits_of_numbers=sum_of_digits_of_numbers+digit;
decrement_of_loop = decrement_of_loop – 1;
The above assignment statements can be written using short hand operators as:
sum_of_digits_of_numbers += digit;
decrement_of_loop –= 1;
Here the special operators ‘+=’ and ‘-=’ are short hand operators.
The general syntax for using short hand operators in assignment statements is:
‘C’ allows us to assign a single value to more than one variable name at a time.
Example: x = y = z = 0.0;
z is assigned a value 0.0, now value of z is assigned to y; and then value of y is assigned to x.
(In the above statements first the variables must be declared and then multiple assignment
statements may be used)
Symbolic Constants:
‘C’ allows defining a variable name as having a constant value using a preprocessor
directive #define
Such preprocessor statements are placed at the beginning of the program and are not a
part of the C program.
Such statements begin with the # symbol and hence do not end with a semicolon.
A symbolic constant can be used to define a numeric constant or a character/string
constant.
Once defined, a symbolic constant’s value can be used at many places in the program.
The syntax of symbolic constant is:
Examples:
#definePI 3.141
#defineCLASS “H Section”
#defineMINI_BAL 500.0
#defineFLAG ‘Y’
Note:
It is sometimes required that the value of a variable should denote a single value
through out the program execution.
A qualifier or modifier ‘const’ is use to do so. This modifier ‘const’ must be placed
before a data type declaration.
Examples:
The above values of variables once initialized by the compiler cannot be changed.
Examples:
Delimiters:
Dept. of CSE, NMAMIT Page 44
These indicate the boundary between the elements of a program
They are also known as separators
They separate constants, variables and statements.
Comma, semicolon, single quotes, double quotes, blank spaces, etc. are the most
commonly used delimiters.
C supports a rich set of operators. Operators are used in programs to manipulate data
variables.
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulation.
Operators usually form a part of the expressions and indicate the type of expressions –
mathematical or logical expressions.
The values that can be operated by these operators are called operands.
An operator that acts on only one kind of operand is known as unary operator.
Types of unary operators are:
(1) Unary Minus (2) Logical NOT operator (3) Bitwise complementation
Let x = 10, y = 5
z = x + (-y)
The logical NOT operator is considered later in Logical operators and bitwise complementation
is considered in bitwise operators.
These operators act on two operands and hence are named as binary operators. Following are the
four types of binary operators:
(1) Arithmetic Operators (3) Logical Operators
(2) Relational Operators (4) Bitwise Operators
The basic arithmetic operations addition, subtraction, multiplication and division can be
performed on any built-in data type of C using these operators.
Another operator, the modulus operator is added to the list of Arithmetic operators. It is used
to find the remainder after integer division.
Operator Meaning
+ Addition
Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus or Modulo Division
Note:
(1) The modulus operator % can be used only for integer operands and not for floating point
operands.
(2) C does not have an operator for exponentiation. This can be performed by a library function
pow().
Arithmetic Expressions:
An expression involving arithmetic operators is called as an arithmetic expression.
These expressions connect one or more operands (integer or real) through arithmetic
operators.
The conventional mathematical expressions that we normally write must be converted into
equivalent C expressions as C compiler understands only the symbols provided in the C
character set.
Example:
2*((i/3)+4*(j-2)) // given i=8 and j=5;
=2*((8/3)+4*(5-2))
=2*(2+4*(5-2))
=2*(2+4*3)
=2*(2+12)
=2*14
=28
C has two very useful operators generally not found in other languages.
They are: Increment Operator denoted by ++
The increment operator ++ adds 1 to the operand while -- subtracts 1 from the operand
associated with it.
These operators act only on integer operands.
Both are unary operators taking the form
int main()
{ Output of the program:
int a=10,b=12;
Given a = 10 and b = 12
printf(“Given a = %d and b =
%d”,a,b); printf(“\na++ = %d”,a++); a++ = 10
printf(“\nb-- = %d”,b--); printf(“\nNow
b-- = 12
a = %d”,a); printf(“\nNow b = %d”,b);
printf(“\n++a = %d”,++a); printf(“\n--b Now a = 11
= %d”,--b); return 0;
Now b = 11
++a = 12
}
--b = 10
These are used to compare two operands. For example, compare the ages of two persons,
compare the prices of two or more items, etc.
They result in either a TRUE (Non-zero) value or FALSE (Zero) value.
Operator Meaning Precedence Associativity
< Lesser than 1 L to R
<= Less than or equal to 1 L to R
> Greater than 1 L to R
>= Greater than or equal to 1 L to R
== Equal to 2 L to R
!= Not equal to 2 L to R
Examples: x>y
age = = 25
cost <= 125.5
Relational Expressions:
A simple relational expression contains only one relational operator. Its syntax is a follows:
where, ae1 and ae2 are arithmetic expressions, which may be simple constants, variables or
combination of them.
When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results compared. That is, arithmetic operators
have a higher priority over relational operators.
Relational expressions are used in decision statements such as if and while to decide the
course of action of a running program.
Suppose a and b are two float point variables holding values 4.5 and 10.0,
Expression Interpretation Value
a <= b TRUE 1
a < -b FALSE 0
a*9 > 0 FALSE 0
a+5<b*2 TRUE 1
a*b == b*a TRUE 1
int main()
{
int a, b;
float n1, n2;
printf(“\n\nEnter two integers and two real numbers:”);
scanf(“%d %d %f %f”,&a, &b, &n1, &n2);
if(a = = b)
Dept. of CSE, NMAMIT Page 53
printf(“\n\n a and b are equal”);
else
printf(“\n\n a and b are unequal”);
return 0;
}
Output of Program:
1. Enter two integers and two real numbers: 10 20 2.5 0.25
a and b are unequal
n1 is greater than n2
Value of Expression
Op1 Op2
Examples Op1 && Op2 Op1 || Op2 !Op1 !Op2 of Logical
T T T T F F
T F F T F T
F T F T T F
F F F F T T
Expressions:
1. if(age > 55 && salary < 50000)
2. if(number < 0 || number > 100)
int main()
{ Output of the program:
int a,b,c;
a = 10; b = 5; 1 1 1
c = a && b;
b = a || b || c;
a = a && b || c;
printf(“\n\n%d %d %d”,a,b,c);
return 0;
}
All the data stored in the computer memory are in sequences of bits (0’s and 1’s).
Some applications require the manipulation of these bits.
Manipulation of individual bits is carried out in machine language or assembly language.
‘C’ provides six operators to perform bitwise operations.
These operators work only with int and char data-types. They cannot be used with floating
point numbers.
5 101
6 110
Examples
Considering normal binary digits.
int a = 6, b = 4;
Equivalent binary value of a = 6 is 0000 0110
Equivalent binary value of b = 4 is 0000 0100
a^b is 0000 0010
Example:
int b = 12;
= 1100 (in binary form)
a = ~b
= 0011
(e) Left Shift Operator (<<) and Right Shift Operator (>>):
Examples: m >> 2
n << 1
a << 2 = (128) = 1 0 0 0 0 0 0 0
int main()
{
unsigned int x,y;
x = 128; y = 32;
printf(“\n\nBefore right shifting, x = %d”,x);
Dept. of CSE, NMAMIT Page 59
printf(“\nBefore left shifting, y = %d”,y);
x = x >> 2;
y = y << 3;
printf(“\n\nAfter right shifting x by 2, x =
%d”,x); printf(“\nAfter left shifting y by 3, y =
%d”,y); return 0;
}
Output of the program:
int main()
{
Output of the program:
int a,b,min,max;
printf(“\n\nEnter two integer Enter two integer numbers: 23 56
numbers:”); scanf(“%d %d”,&a,&b);
printf(“\n\na = %d b = %d”,a,b);
max = a > b ? a : b; min = a < b ? a : a = 23 b = 56
b;
printf(“\n\nMaximum of a and b is
%d”,max); printf(“\nMinimum of a and b is Maximum of a and b is 56
%d”,min); return 0;
Minimum of a and b is 23
}
Examples:
a = sizeof (int);
y = sizeof (avg);
#include <stdio.h>
int main()
{
int x;
Output of the program:
float y;
char ch = ‘y’; Size of x = 2 Size
x = 10; y = 100.0;
of y = 4 Size of
printf(“\n\nSize of x = %d”,sizeof(x));
printf(“\nSize of y = %d”,sizeof(y)); ch = 1 Size of
printf(“\nSize of ch = %d”,sizeof(ch));
double = 8
printf(“\nSize of double = %d”,sizeof(double));
return 0;
}
#include <stdio.h>
int main()
{
int a,b,temp;
b = (a = 20,a + 10);
printf(“\n\nBefore swapping, a = %d & b = %d”,a,b);
temp = a, a = b, b = temp;
printf(“\nAfter swapping, a = %d & b = %d”,a,b);
return 0;
Output of the program:
}
Before swapping, a = 20 & b = 30
C EXPRESSIONS
When an expression can be interpreted in more than one way, there are rules that govern how the
expression gets interpreted by the compiler. Such expressions follow C’s precedence and
associativity rules. The precedence of operators determine a rank for the operators.
For example, the expression a * b + c can be interpreted as (a * b) + c or a * (b + c), but the first
interpretation is the one that is used because the multiplication operator has higher precedence
than addition.
The process of converting one type of data type to another, say change int to float or float
to int is known as data type conversion or type casting.
The general form of type casting is
Syntax:
(data type)variable
Example:
int a = 3; int a = 3;
float sum;
sum = 20/a;
float sum;
………………………………
This type of conversion is usually performed by the compiler when necessary without any
commands by the user. Thus it is also called "Automatic Type Conversion". The compiler
usually performs this type of conversion when a particular expression contains more than one
data type. The compiler first performs integer promotion; if the operands still have different
types, then they are converted to the type that appears highest in the following hierarchy.
int main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
Output:
Value of sum : 116.000000
Here, first c gets converted to integer, but as the final value is double, usual arithmetic
conversion takes place and the compiler converts i and c into 'float' and adds them yielding a
'float' result.
In Explicit type conversion, the user explicitly defines within the program the datatype, to which
the operands/variables of the expression need to be converted.
Dept. of CSE, NMAMIT Page 67
Example:
#include <stdio.h>
int main()
{
double a = 4.5;
double b = 4.6;
double c = 4.9;
int result;
result = (int)a + (int)b + (int)c; //explicitly defined by
user printf("Result = %d", result); return 0;
Output:
Result = 12
Here, output result is 12 because in the resulting expression the user has explicitly defined the
operands (variables) as integer data type. Hence, there is no implicit conversion of data type by
the compiler.
(Additional Information)
Mathematical functions:
C provides a large number of mathematical functions which readily calculate the values of
trigonometric, hyperbolic and other functions.
All these functions are defined in the header file math.h.
Some of the most commonly used mathematical functions are:
Function Return type Meaning
acos(x) double Arc cosine of x (cos-1 x)
asin(x) double Arc sine of x (sin-1 x
atan(x) double Arc tangent of x (tan-1x)
Trigonometric
atan2(x,y) double Arc tangent of (x/y) [tan-1(x/y)]
cos(x) double Cosine of (x)
sin(x) double Sine of (x)
Reading, processing and writing are the three essential functions of a computer.
Every computer program has to take some data as input and write/print/display
the processed data as output.
1. Non-Interactive method:
Example:
2. Interactive Method:
Data is supplied to the computer by the user through standard input device like the
key board.
gets() puts()
Note that the functions getch() and getche() are defined in another header
file by name conio.h
Formatted I/O functions: These enable the user to specify the type of data and the way in
which it should be read or written out.
Unformatted I/O functions: Using these types of functions, the user cannot specify the type
getchar(),getch(), gets(),
putchar(), puts() etc.
Unformatted
getche(), etc.
FORMATTED INPUT
It refers to the input of one or more data types arranged in a particular format.
“control string” contains one or more character groups (or field specifiers) which direct
the interpretation of input data.
address_list OR &var1, &var2,… ............................... &varn specify the address locations of
Without the optional number which specifies the field width, the character group format is
The table below shows a list of the character groups (or field specifiers) commonly used:
Character group Meaning
%p Read a pointer
%s Read a string
Examples of scanf()functions:
scanf(“%d%f%c”, &n1,&n2,&ch);
scanf(“%d,%f,%c”,&num,&avg,&c1);
scanf(“%d %f %s”,&a, &total, msg);
The character group (or the field specifier) for reading the integer number is:
% w d
scanf(“%2d %5d”,&num1,&num2);
When the computer executes this statement, it waits for the user to enter values for
the variables num1and num2.
These kinds of errors can be eliminated if we use character groups without specifying the field
width (w).
Thus the statement scanf(“%d %d”,&num1,&num2);
will read the data 3142650 correctly and assign 31426 to num1and 50 to num2.
If we enter a floating point number instead of an integer, the fractional part may be ignored
and scanf() may skip reading further input.
In place of the optional field width specifier (w) if we use a asterisk * symbol, that particular
input field will be skipped.
if we enter 123 45 97, 123 will be assigned to a and 97 will be assigned to b, 45 will not
be assigned to b and will be skipped. garbage value will be assigned to c.
The data type character ‘d’ may be preceded by the letter ‘l’ (i.e., % ld) to read long integers.
Example:
#include <stdio.h>
int main()
{
int a,b,c,x,y,z;
return 0;
Output of program:
x=89 y=123
Real numbers (both fractional and exponential notations) can be input by using
int main()
{
float x,y;
double p,q;
printf("\n\n\tENTER THE VALUES OF X AND Y:");
scanf("%f %g",&x, &y);
printf("\n\t x=%f\n\ty=%f",x,y);
getch();
Output of program:
x=12.345600
p=1.123456789000
q=2.9876543210e+00
The simplest way of reading a single character from the standard input device
(Keyboard) is by using the function getchar() available in the header file stdio.h.
The syntax of the getchar function is:
var_name = getchar();
When this statement is encountered, the computer waits until a key is pressed and
then assigns this character as a value to the getchar function.
For example,
char ch;
ch = getchar();
Suppose we enter the character ‘y’ through the keyboard, ‘y’ is assigned to ch.
Since getchar is a function, it is used with a set of parenthesis ()
Other functions that are used to read single variables are (available in conio.h):
getch(): Enables the user to enter only one character through the keyboard
without pressing the enter key.
getche(): Enables the user to enter only one character through the keyboard
without pressing the enter key, and will echo (display on monitor) the character
typed in. (The last letter ‘e’ in getche()stands for echo)
Dept. of CSE, NMAMIT Page 80
The getchar function when executed waits until any character of the keyboard is
keyed in followed by pressing the ENTER (\n) key. Only after ENTER key is pressed,
execution is returned to the next statement of program.
The getchar function echoes (displays on monitor) the character that has been
keyed in.
We may use the scanf() function also to read a single character. For the above
example the use of scanf()would be:
char ch;
scanf(“%c”,&ch);
Example:
#include<stdio.h>
int main()
{
char ans;
printf(“\n\n\tWould you like to know my
name?”); printf(“\n\tEnter Y for YES and N for
NO:”); ans=getchar();
if(ans == ‘Y’ || ans == ‘y’)
{
printf(“\n\n\tMy name is BUSY BEE...!!!”);
getch();
}
else
{
printf(“\n\n\tYou are good for nothing...!!!”);
Suppose we want to read the string “Handsome” and assign it to a string variable
name
char name[20];
scanf(“%10c”,name); OR scanf(“%s”,name);
Instead of the character group %10cif %6cis used, then only first 6 characters
of Handsome i.e., Handso will be assigned to name.
Suppose for the above first scanf statement we enter Balaguru Swamy, only first
10 characters will be stored in name i.e., Balaguru S
‘C’ supports some special character groups for string variables only. They are
Example:
Special character
Meaning
groups for strings
Example:
#include <stdio.h>
#include <conio.h>
int main()
{
int no;
char name1[15],name2[15],name3[15];
printf(“\n\t%d%15s”,no,name2);
getch();
printf(“\n\t%d %15s”,no,name3);
return 0;
The scanf()function can be used to read more than one type of data (mixed mode).
In such situations, the programmer should take care of the
(1) number of input variables, (2) data type and (3) their order.
If there is a type mismatch, scanf()function does not read the values input.
For example, consider the scanf() statement
scanf(“%d %c %f %s”,&count,&code,&ratio,name);
The input values entered must be of the form 15 p 1.575 coffee for successful
reading of the values respectively to count, code, ratio and name.
For the above example, on successful reading, the scanf() function will return a value
4 (i.e., the number of data types successfully read).
#include <stdio.h>
int main()
{
int a,r; float b; char c;
printf(“\n\n\tEnter the values of a, b and c:”);
r=scanf(“%d %f %c”,&a,&b,&c);
if(r==3)
printf(“\n\ta=%d b=%f c=%c”,a,b,c);
else
printf(“\n\tERROR IN INPUT...!!”);
Output of program:
12 3.45 A
a=12 b=3.45 c=A
FORMATTED OUTPUT
It refers to display of the processed values or results and messages on the display
screen according to the format (way of appearance) as desired by the programmer.
It is highly desirable that the messages and values must be displayed in the most
legible (understandable) form.
The printf() function is a standard formatted output function defined under the header
file stdio.h.
The control string indicates how many arguments follow and what their
types are.
Control string consists of three types of items:
1. Characters that will be placed on the screen as they appear
2. Character groups (format specifiers) that define the output format
for display of each item.
3. Escape sequence (backslash constants) such as \n, \t, \b, etc.
arg1, arg2,…….argn are the list of arguments (variables) whose values are
formatted and printed according to the specifications of the control string.
%w.p type_specifier
where,
w is an integer number that specifies the total number of columns of output value
p is another integer which specifies the number of digits to the right of the decimal
point of the floating point number.
or
it is the number of characters to be printed from a string.
Both w and p are optional.
%wd
where,
w specifies the minimum field width for output. However is a number is greater
than the specified field width, it will be printed in full overriding the minimum
specification.
d specifies that the value to be printed is an integer.
Examples :
printf(“%d”,9876) 9 8 7 6
printf(“%6d”,9876) 9 8 7 6
printf(“%2d”,9876) 9 8 7 6
printf(“%-6d”,9876) 9 8 7 6
printf(“%06d”,9876) 0 0 9 8 7 6
The format specification for a floating point number in decimal notation is
%w.pf
The format specification for a floating point number in exponential notation is
%w.pe
where,
w is an integer which specifies the minimum number of positions that are to be
used for the display of the value.
p is an integer which specifies the precision i.e., the number of digits to
be displayed after the decimal point.
A special field specification character “%*.*f”that lets the user define the field size during
run-time may also be used.
is same as printf(“%7.2f”,num);
The advantage of this format is that the values for the width and precision may be supplied
during run-time, thus making the format a dynamic one.
printf(“%7.4f”,y); 9 8 . 7 6 5 4
printf(“%7.2f”,y); 9 8 . 7 7
printf(“%-7.2f”,y); 9 8 . 7 7
printf(“%f”,y); 9 8 . 7 6 5 4
printf(“%10.2e”,y); 9 . 8 8 e + 0 1
printf(“%11.4e”,-y); - 9 . 8 7 6 5 e + 0 1
printf(“%-10.2e”,y); 9 . 8 8 e + 0 1
printf(“%e”,y); 9 . 8 7 6 5 4 0 e + 0 1
Printing of Strings:
Using unformatted output, a single character can be output by using the function
putchar() available under the header file stdio.h.
The syntax of putchar()is:
putchar(var_name);
This statement displays the character contained in var_nameon the display monitor.
This statement displays the string on to the display terminal and appends a
new line character(\n) in the end.
‘C’ has a set of library functions which are used to test the type of character, i.e., whether
a character is a lower case or upper case alphabet or a digit or printable character, etc.
isdigit(c) Is c a digit?