Post on 28-Feb-2021
C Programming for Problem Solving 18CPS23
MODULE 1
Dept. of CSE, BNMIT 2018-19 Page 1
C Programming for Problem Solving 18CPS23
CHAPTER I:
Introduction_on to computer hardware and software_
1 Computer Generations:
Computers are such an integral part of our everyday life now most people take them and
What they have added to life totally for granted more so the generation who have grown from infancy
within the global desktop and laptop revolution since the 1980, the history of the computer goes back
several decades however and there are five definable generations of computers.
Each generation is defined by a significant technological development that changes fundamentally
how computers operate - leading to more compact, less expensive, but more powerful, efficient and
robust machines.
1940 - 1956: First Generation - Vacuum Tubes
These early computers used vacuum tubes as circuitry and magnetic drums for memory, As a result
they were enormous, literally taking up entire rooms. These were inefficient materials which generated
a lot of heat, sucked huge electricity and subsequently generated a lot of heat which caused ongoing
breakdowns.
These first generation computers relied on _machine language' (which is the most basic programming
language that can be understood by computers). These computers were limited to solving one problem
at a time. Input was based on punched cards and paper tape. Output came out on print-outs. The two
notable machines of this era were the UNIVAC and ENIAC machines the UNIVAC is the first every
commercial computer which was purchased in 1951 by a business - the US Census bureau.
Fig 1.1: Vacuum tubes
Dept. of CSE, BNMIT 2018-19 Page 2
C Programming for Problem Solving 18CPS23
Operation continued without the benefit of an operating system for a time. The mode was
called "closed shop" and was characterized by the appearance of hired operators who would
select the job to be run, initial program load the system, run the user‘s program, and then select
another job, and so forth. Programs began to be written in higher level, procedure-oriented
languages, and thus the operator‘s routine expanded. The operator now selected a job, ran the
translation program to assemble or compile the source program, and combined the translated
object program along with any existing library programs that the program might need for input to
the linking program, loaded and ran the composite linked program, and then handled the next job
in a similar fashion. Application programs were run one at a time, and were translated with
absolute computer addresses. There was no provision for moving a program to different location
in storage for any reason. Similarly, a program bound to specific devices could not be run at all if
any of these devices were busy or broken.
1956 - 1963: Second Generation - Transistors
The replacement of vacuum tubes by transistors saw the advent of the second generation of
computing. Although first invented in 1947, transistors weren't used significantly in computers
until the end of the 1950s. They were a big improvement over the vacuum tube, despite still
subjecting computers to damaging levels of heat. However they were hugely superior to the
vacuum tubes making computers smaller, faster, cheaper and less heavy on electricity use. They
still relied on punched card for input/printouts
The language evolved from cryptic binary language to symbolic(_assembly') languages, This
meant programmers could create instructions in words. About the same time high level
programming languages were being developed (early versions of COBOL and FORTRAN).
Transistor-driven machines were the first computers to store instructions into their memories
moving from magnetic drum to magnetic core _technology' .
The second generation was a period of intense operating system development. Also it was
the period for sequential batch processing. Researchers began to experiment with
multiprogramming and multiprocessing.
Dept. of CSE, BNMIT 2018-19 Page 3
C Programming for Problem Solving 18CPS23
Fig 1.2 Transistors
1964 - 1971: Third Generation - Integrated Circuits
By this phase, transistors were now being miniaturized and put on silicon chips (called
Semi conductors). This led to a massive increase in speed and efficiency of these machines. These
were the first computers where users interacted using keyboards and monitors which interfaced
with an operating system, a significant leap up from the punch cards and printouts.
This enabled these machines to run several applications at once using a central program which
functioned to monitor memory.
Fig. 1.3: Third generation Computers
1972 - 2010: Fourth Generation -Microprocessors
This revolution can be summed in one word: Intel. The chip-maker developed the Intel 4004 chip in
1971, which positioned all computer components (CPU, memory, input/output controls) onto a single
chip. What filled a room in the 19405 now fit in the palm of the hand The Intel chip housed thousands of
integrated circuits. The year 1981 saw the first ever computer (IBM) specifically designed for home use
and 1984 saw the Macintosh introduced by Apple. Microprocessors even moved beyond the realm of
computers and into an increasing number of everyday products.
Dept. of CSE, BNMIT 2018-19 Page 4
C Programming for Problem Solving 18CPS23
The increased power of these small computers meant they could be linked, creating networks. Which
ultimately led to the development, birth and rapid evolution of the Internet Other major advances
during this period have been the Graphical user interface (GUI), the mouse and more recently the
astounding advances in lap-'top capability and hand" held devices.
AI is a reality made possible by using parallel processing and superconductors. Leaning to the
future, computers will be radically transformed again by quantum computation, molecular and nano technology.
The essence of fifth generation will be using these technologies to ultimately create machines
which can process and respond to natural language, and have capability to learn and organize
themselves,
Fig. 1.5: Artificial Intelligence
2 Computer Types:-
Since the advent of the first computer different types and sizes of computers are offering
different services. Computers can be as big as occupying a large building and as small as a
laptop or a microcontroller in mobile & embedded systems.
The four basic types of computers are as under:
1. Supercomputer
2. Mainframe Computer
3. Minicomputer
4. Microcomputer
1. Supercomputer
The most powerful computers in terms of performance and data processing are the
Supercomputers. These are specialized and task specific computers used by large organizations.
Dept. of CSE, BNMIT 2018-19 Page 5
C Programming for Problem Solving 18CPS23
These computers are used for research and exploration purposes, like NASA uses
supercomputers for launching space shuttles, controlling them and for space exploration
purpose.
Fig 1.6 Super Computer
2. Mainframe Computer
Although Mainframes are not as powerful as supercomputers, but certainly they are quite
expensive nonetheless, and many large firms & government organizations uses Mainframes
to run their business operations. The Mainframe computers can be accommodated in large
air- conditioned rooms because of its size. Super-computers are the fastest computers with
large data storage capacity, Mainframes can also process & store large amount of data. Banks
educational institutions & insurance companies use mainframe computers to store data about
their customers, students & insurance policy holders.
Fig 1.7 Mainframe computer
3. Mini Computer
Minicomputers are used by small businesses & firms. Minicomputers are also called as "Midrange
Computers" These are small machines and can be accommodated on a disk with not as processing
and data storage capabilities as super-computers & Mainframes.
Dept. of CSE, BNMIT 2018-19 Page 6
C Programming for Problem Solving 18CPS23 These computers are not designed for a single user. Individual departments of a large company or
organizations use Mini-computers for specific purposes. For example, a production department
can use Mini-computers for monitoring certain production process.
Fig. 1.8: Minicomputer
4. Micro Computer
Desktop computers, laptops, personal digital assistant (PDA), tablets & smart phones are
all types of microcomputers. The micro-'computers are widely used & the fastest growing
computers. These computers are the cheapest among the other three types of computers.
The Micro'-computers are specially designed for general usage like entertainment,
education and work purposes. Well known manufacturers of Micro-'computer are Dell,
Apple, Samsung, Sony& Toshiba. Desktop computers, Gaming consoles, Sound &
Navigation system of a car, Notebooks, Notebooks, PDA's, Tablet PC's, Smartphone’s,
Calculators are all type of Microcomputers.
Fig. 1.9: Microcomputer
Bits, bytes and words
A bit is a Binary digit. So a bit is a zero or a one. Bits can be implemented in computer hardware
using switches. If the switch is on then the bit is one and if the switch is off then the bit is zero. A bit
is limited to representing two values.
Since the alphabet contains more than two letters, a letter cannot be represented by a bit. A
Dept. of CSE, BNMIT 2018-19 Page 7
C Programming for Problem Solving 18CPS23
byte is a sequence of bits. Since the mid 1960's a byte has been 8 bits in length. 01000001 is an
example of a byte. Since there are 8 bits in a byte there are 28 different possible sequences for one
byte, ranging from 00000000 HI I ,UH This means that a byte can be use to represent any type of
value with no more than 28 56 possible values. Since the number of things that you can enter on a
computer keyboard is smaller than 256(including all key stoke pairs, like shift or control plus
another key), a code for a keystroke is represented with a code within a byte.
Since characters(letters, decimal digits and special characters such as punctuation marks,
etc) can be represented with bytes, a standard is needed to ensure that the code that's used on your
computer is the same as the code that is used on mine. There are two standard codes that use one
byte to represent a character, ASCII and EBCDIC. ASCIL the American Standard Code for
information interchange is the code that is most commonly used EBCDlC, Extended Binary Coded
Decimal lnterchange Code, was used by IBM on its large mainframe computers in the past.
Wikipedia has more than you want to know about ASCII and EBCDIC.
A word is the number of bits that are manipulated as a unit by the particular CPU of the
computer, Today most CPUs have a word size of 32 or 64 bits. For example, the notebook
computer that I bought in May 2008 contains a core 2 duo 64 bit processor. Data is fetched from
memory to the processor in word size chunks and manipulated by the ALU in word size chunks.
BASIC COMPUTER ORGANIZATION:
A standard fully featured desktop configuration has basically four types of featured devices
1. Input Devices
2. Output Devices
3. Memory
4. Storage Devices
Dept. of CSE, BNMIT 2018-19 Page 8
C Programming for Problem Solving 18CPS23
Introduction to CPU
CPU
The Arithmetic / Logic Unit (ALU)
The Control Unit
Main Memory
External Memory
Input / Output Devices
The System Bus
CPU OPERATION
The fundamental operation of most CPUs
- To execute a sequence of stored instructions called a program.
1. The program is represented by a series of numbers that are kept in some kind of computer
memory.
2. There are four steps that nearly all CPUs use in their operation: fetch, decode, execute, and
write back.
3. Fetch:
Retrieving an instruction from program memory.
The location in program memory is determined by a program counter (PC)
After an instruction is fetched, the PC is incremented by the length of the instruction
word in terms of memory units.
Decode :
1. The instruction is broken up into parts that have significance to other portions of the
CPU.
2. The way in which the numerical instruction value is interpreted is defined by the CPU's
instruction set architecture (ISA).
Dept. of CSE, BNMIT 2018-19 Page 9
C Programming for Problem Solving 18CPS23
3. Opcode, indicates which operation to perform.
4. The remaining parts of the number usually provide information required for that
instruction, such as operands for an addition operation.
5. Such operands may be given as a constant value or as a place to locate a value: a register
or a memory address, as determined by some addressing mode.
Execute :
1. During this step, various portions of the CPU are connected so they can perform the
desired operation.
2. If, for instance, an addition operation was requested, an arithmetic logic unit (ALU) will
be connected to a set of inputs and a set of outputs.
3. The inputs provide the numbers to be added, and the outputs will contain the final sum.
4. If the addition operation produces a result too large for the CPU to handle, an arithmetic
overflow flag in a flags register may also be set.
Write back :
1. Simply "writes back" the results of the execute step to some form of memory.
2. Very often the results are written to some internal CPU register for quick access by
subsequent instructions.
3. In other cases results may be written to slower, but cheaper and larger, main memory.
Some types of instructions manipulate the program counter rather than directly produce result
data.
MEMORY OR PRIMARY STORAGE :
Purpose of Storage
The fundamental components of a general-purpose computer are arithmetic and logic unit,
control circuitry, storage space, and input/output devices. If storage was removed, the device we
had would be a simple calculator instead of a computer. The ability to store instructions that
form a computer program, and the information that the instructions manipulate is what makes
stored program architecture computers versatile.
Dept. of CSE, BNMIT 2018-19 Page 10
C Programming for Problem Solving 18CPS23
Primary Storage
Primary storage is directly connected to the central processing unit of the computer. It must be
present for the CPU to function correctly, just as in a biological analogy the lungs must be
present (for oxygen storage) for the heart to function (to pump and oxygenate the blood). As
shown in the diagram, primary storage typically consists of three kinds of storage:
Dept. of CSE, BNMIT 2018-19 Page 11
C Programming for Problem Solving 18CPS23
Processors Register
It is the internal to the central processing unit. Registers contain information that the arithmetic
and logic unit needs to carry out the current instruction. They are technically the fastest of all
forms of computer storage.
Main memory
It contains the programs that are currently being run and the data the programs are operating on.
The arithmetic and logic unit can very quickly transfer information between a processor register
and locations in main storage, also known as a "memory addresses". In modern computers,
electronic solid-state random access memory is used for main storage, and is directly connected
to the CPU via a "memory bus" and a "data bus".
Cache memory
It is a special type of internal memory used by many central processing units to increase their
performance or "throughput". Some of the information in the main memory is duplicated in the
cache memory, which is slightly slower but of much greater capacity than the processor registers,
and faster but much smaller than main memory.
Memory
Memory is often used as a shorter synonym for Random Access Memory (RAM). This kind of
memory is located on one or more microchips that are physically close to the microprocessor in
your computer. Most desktop and notebook computers sold today include at least 512 megabytes
of RAM (which is really the minimum to be able to install an operating system). They are
upgradeable, so you can add more when your computer runs really slowly.
The more RAM you have, the less frequently the computer has to access instructions and data
from the more slowly accessed hard disk form of storage. Memory should be distinguished from
Dept. of CSE, BNMIT 2018-19 Page 12
C Programming for Problem Solving 18CPS23
storage, or the physical medium that holds the much larger amounts of data that won't fit into
RAM and may not be immediately needed there.
Storage devices include hard disks, floppy disks, CDROMs, and tape backup systems. The terms
auxiliary storage, auxiliary memory, and secondary memory have also been used for this kind of
data repository.
RAM is temporary memory and is erased when you turn off your computer, so remember to save
your work to a permanent form of storage space like those mentioned above before exiting
programs or turning off your computer.
Dept. of CSE, BNMIT 2018-19 Page 13
C Programming for Problem Solving 18CPS23
TYPES OF RAM:
There are two types of RAM used in PCs - Dynamic and Static RAM.
Dynamic RAM (DRAM): The information stored in Dynamic RAM has to be refreshed after
every few milliseconds otherwise it will get erased. DRAM has higher storage capacity and is
cheaper than Static RAM.
Static RAM (SRAM): The information stored in Static RAM need not be refreshed, but it remains
stable as long as power supply is provided. SRAM is costlier but has higher speed than DRAM.
Additional kinds of integrated and quickly accessible memory are Read Only Memory (ROM),
Programmable ROM (PROM), and Erasable Programmable ROM (EPROM). These are used to
keep special programs and data, such as the BIOS, that need to be in your computer all the time.
ROM is "built-in" computer memory containing data that normally can only be read, not written
to (hence the name read only).
ROM contains the programming that allows your computer to be "booted up" or regenerated each
time you turn it on. Unlike a computer's random access memory (RAM), the data in ROM is not lost
when the computer power is turned off. The ROM is sustained by a small long life battery in your
computer called the CMOS battery. If you ever do the hardware setup procedure with
your computer, you effectively will be writing to ROM. It is non volatile, but not suited to
storage of large quantities of data because it is expensive to produce. Typically, ROM must also
be completely erased before it can be rewritten,
PROM (Programmable Read Only Memory)
A variation of the ROM chip is programmable read only memory. PROM can be programmed to
record information using a facility known as PROM-programmer. However once the chip has
Dept. of CSE, BNMIT 2018-19 Page 14
C Programming for Problem Solving 18CPS23
been programmed the recorded information cannot be changed, i.e. the PROM becomes a ROM
and the information can only be read.
EPROM (Erasable Programmable Read Only Memory)
As the name suggests the Erasable Programmable Read Only Memory, information can be
erased and the chip programmed a new to record different information using a special PROM-
Programmer. When EPROM is in use information can only be read and the information remains
on the chip until it is erased.
STORAGE DEVICES
The purpose of storage in a computer is to hold data or information and get that data to the CPU
as quickly as possible when it is needed. Computers use disks for storage: hard disks that are
located inside the computer, and floppy or compact disks that are used externally.
Dept. of CSE, BNMIT 2018-19 Page 15
C Programming for Problem Solving 18CPS23
• Computers Method of storing data & information for long term basis i.e. even after PC is
switched off.
• It is non - volatile
• Can be easily removed and moved & attached to some other device
• Memory capacity can be extended to a greater extent
• Cheaper than primary memory
Storage Involves Two
Processes a) Writing data b) Reading data
Floppy Disks
The floppy disk drive (FDD) was invented at IBM by Alan Shugart in 1967. The first floppy
drives used an 8-inch disk (later called a "diskette" as it got smaller), which evolved into the
5.25-inch disk that was used on the first IBM Personal Computer in August 1981. The 5.25-inch
disk held 360 kilobytes compared to the 1.44 megabyte capacity of today's 3.5-inch diskette.
The 5.25-inch disks were dubbed "floppy" because the diskette packaging was a very flexible
plastic envelope, unlike the rigid case used to hold today's 3.5-inch diskettes.
By the mid-1980s, the improved designs of the read/write heads, along with improvements in the
magnetic recording media, led to the less-flexible, 3.5-inch, 1.44-megabyte (MB) capacity FDD
in use today. For a few years, computers had both FDD sizes (3.5-inch and 5.25-inch). But by the
mid-1990s, the 5.25-inch version had fallen out of popularity, partly because the diskette's
recording surface could easily become contaminated by fingerprints through the open access
area.
When you look at a floppy disk, you'll see a plastic case that measures 3 1/2 by 5 inches. Inside
that case is a very thin piece of plastic that is coated with microscopic iron particles. This disk is
Dept. of CSE, BNMIT 2018-19 Page 16
C Programming for Problem Solving 18CPS23
much like the tape inside a video or audio cassette. Basically, a floppy disk drive reads and
writes data to a small, circular piece of metal-coated plastic similar to audio cassette tape.
At one end of it is a small metal cover with a rectangular hole in it. That cover can be moved
aside to show the flexible disk inside. But never touch the inner disk - you could damage the data
that is stored on it. On one side of the floppy disk is a place for a label. On the other side is a
silver circle with two holes in it. When the disk is inserted into the disk drive, the drive hooks
into those holes to spin the circle. This causes the disk inside to spin at about 300 rpm! At the
same time, the silver metal cover on the end is pushed aside so that the head in the disk drive can
read and write to the disk.
Floppy disks are the smallest type of storage, holding only 1.44MB.
3.5-inch Diskettes (Floppy Disks) features:
• Spin rate: app. 300 revolutions per minute (rpm)
• High density (HD) disks more common today than older, double density (DD) disks
• Storage Capacity of HD disks is 1.44 MB
Dept. of CSE, BNMIT 2018-19 Page 17
C Programming for Problem Solving 18CPS23
Floppy Disk Drive Terminology
Floppy disk - Also called diskette. The common size is 3.5 inches.
Floppy disk drive - The electromechanical device that reads and writes floppy disks.
Track - Concentric ring of data on a side of a disk.
Sector - A subset of a track, similar to wedge or a slice of pie.
It consists of a read/write head and a motor rotating the disk at a high speed of about 300
rotations per minute. It can be fitted inside the cabinet of the computer and from outside, the slit
where the disk is to be inserted, is visible. When the disk drive is closed after inserting the floppy
inside, the monitor catches the disk through the Central of Disk hub, and then it starts rotating.
There are two read/write heads depending upon the floppy being one sided or two sided. The
head consists of a read/write coil wound on a ring of magnetic material. During write operation,
when the current passes in one direction, through the coil, the disk surface touching the head is
magnetized in one direction. For reading the data, the procedure is reverse. I.e. the magnetized
spots on the disk touching the read/write head induce the electronic pulses, which are sent to
CPU.
The major parts of a FDD include:
Read/Write Heads: Located on both sides of a diskette, they move together on the same
assembly. The heads are not directly opposite each other in an effort to prevent interaction
between write operations on each of the two media surfaces. The same head is used for reading
and writing, while a second, wider head is used for erasing a track just prior to it being written.
This allows the data to be written on a wider "clean slate," without interfering with the analog
data on an adjacent track.
Dept. of CSE, BNMIT 2018-19 Page 18
C Programming for Problem Solving 18CPS23
Drive Motor: A very small spindle motor engages the metal hub at the center of the diskette,
spinning it at either 300 or 360 rotations per minute (RPM).
Stepper Motor: This motor makes a precise number of stepped revolutions to move the
read/write head assembly to the proper track position. The read/write head assembly is fastened
to the stepper motor shaft.
Mechanical Frame: A system of levers that opens the little protective window on the diskette to
allow the read/write heads to touch the dual-sided diskette media. An external button allows the
diskette to be ejected, at which point the spring-loaded protective window on the diskette closes.
Circuit Board: Contains all of the electronics to handle the data read from or written to the
diskette. It also controls the stepper-motor control circuits used to move the read/write heads to
each track, as well as the movement of the read/write heads toward the diskette surface.
Dept. of CSE, BNMIT 2018-19 Page 19
C Programming for Problem Solving 18CPS23
Electronic optics check for the presence of an opening in the lower corner of a 3.5-inch diskette
(or a notch in the side of a 5.25-inch diskette) to see if the user wants to prevent data from being
written on it.
Hard Disks
Your computer uses two types of memory: primary memory which is stored on chips located on
the motherboard, and secondary memory that is stored in the hard drive. Primary memory holds
all of the essential memory that tells your computer how to be a computer. Secondary memory
holds the information that you store in the computer.
Inside the hard disk drive case you will find circular disks that are made from polished steel. On
the disks, there are many tracks or cylinders. Within the hard drive, an electronic reading/writing
device called the head passes back and forth over the cylinders, reading information from the
disk or writing information to it. Hard drives spin at 3600 or more rpm (Revolutions Per Minute)
- that means that in one minute, the hard drive spins around over 7200 times!
Optical Storage
• Compact Disk Read-Only Memory (CD-ROM)
• CD-Recordable (CD-R)/CD-Rewritable (CD-RW)
• Digital Video Disk Read-Only Memory (DVD-ROM)
• DVD Recordable (DVD-R/DVD Rewritable (DVD-RW)
• Photo CD
Optical Storage Devices Data is stored on a reflective surface so it can be read by a beam of
laser light. Two Kinds of Optical Storage Devices
• CD-ROM (compact disk read-only memory)
• DVD-ROM (digital video disk read-only memory)
Compact Disks
Dept. of CSE, BNMIT 2018-19 Page 20
C Programming for Problem Solving 18CPS23
Instead of electromagnetism, CDs use pits (microscopic indentations) and lands (flat surfaces) to
store information much the same way floppies and hard disks use magnetic and non-magnetic
storage. Inside the CD-Rom is a laser that reflects light off of the surface of the disk to an electric
eye. The pattern of reflected light (pit) and no reflected light (land) creates a code that represents
data.
CDs usually store about 650MB. This is quite a bit more than the 1.44MB that a floppy disk
stores. A DVD or Digital Video Disk holds even more information than a CD, because the DVD
can store information on two levels, in smaller pits or sometimes on both sides.
Recordable Optical Technologies
• CD-Recordable (CD-R)
• CD-Rewritable (CD-RW)
•
•
•
PhotoCD
DVD-Recordable (DVD-R)
DVD-RAM
CD ROM - Compact Disc Read Only Memory.
Unlike magnetic storage device which store data on multiple concentric tracks, all CD formats
store data on one physical track, which spirals continuously from the center to the outer edge of
the recording area. Data resides on the thin aluminum substrate immediately beneath the label.
The data on the CD is recorded as a series of microscopic pits and lands physically embossed on
an aluminum substrate. Optical drives use a low power laser to read data from those discs
without physical contact between the head and the disc which contributes to the high reliability
and permanence of storage device.
Dept. of CSE, BNMIT 2018-19 Page 21
C Programming for Problem Solving 18CPS23
To write the data on a CD a higher power laser are used to record the data on a CD. It creates the
pits and land on aluminum substrate. The data is stored permanently on the disc. These types of
discs are called as WORM (Write Once Read Many). Data written to CD cannot subsequently be
deleted or overwritten which can be classified as advantage or disadvantage depending upon the
requirement of the user. However if the CD is partially filled then the more data can be added to
it later on till it is full. CDs are usually cheap and cost effective in terms of storage capacity and
transferring the data.
The CD‘s were further developed where the data could be deleted and re written. These types of
CDs are called as CD Rewritable. These types of discs can be used by deleting the data and
making the space for new data. These CD‘s can be written and rewritten at least 1000 times.
CD ROM Drive
CD ROM drives are so well standardized and have become so ubiquitous that many treat them as
commodity items. Although CD ROM drives differ in reliability, which standards they support
and numerous other respects, there are two important performance measures.
Data transfer rate
Average access
Data transfer rate: Data transfer rate means how fast the drive delivers sequential data to the
interface. This rate is determined by drive rotation speed, and is rated by a number followed by
‗X‘. All the other things equal, a 32X drive delivers data twice the speed of a 16X drive. Fast
data transfer rate is most important when the drive is used to transfer the large file or many
sequential smaller files. For example: Gaming video.
CD ROM drive transfers the data at some integer multiple of this basic 150 KB/s 1X rate. Rather
than designating drives by actual KB/s output drive manufacturers use a multiple of the standard
1X rate. For example: a 12X drive transfer data at (12*150KB/s) 1800 KB/s and so on.
Dept. of CSE, BNMIT 2018-19 Page 22
C Programming for Problem Solving 18CPS23
The data on a CD is saved on tracks, which spirals from the center of the CD to outer edge. The
portions of the tracks towards center are shorter than those towards the edge. Moving the data
Dept. of CSE, BNMIT 2018-19 Page 23
C Programming for Problem Solving 18CPS23
under the head at a constant rate requires spinning the disc faster as the head moves from the
center where there is less data per revolution to the edge where there is more data. Hence the
rotation rate of the disc changes as it progresses from inner to outer portions of the disc.
CD Writers
CD recordable and CD rewritable drives are collectively called as CD writers or CD burners.
They are essentially CD ROM drives with one difference. They have a more powerful laser that,
in addition to reading discs, can record data to special CD media.
Pen Drives / Flash Drives
Pen Drives / Flash Drives are flash memory storage devices.
They are faster, portable and have a capability of storing large data.
It consists of a small printed circuit board with a LED encased in a robust plastic
The male type connector is used to connect to the host PC
They are also used a MP3 players
INPUT DEVICES
Anything that feeds the data into the computer. This data can be in alpha-numeric form which
needs to be keyed-in or in its very basic natural form i.e. hear, smell, touch, see; taste & the sixth
sense …feel?
Typical input devices are:
1. Keyboard 2. Mouse
3. Joystick 4. Digitizing Tablet
5. Touch Sensitive Screen 6. Light Pen
Dept. of CSE, BNMIT 2018-19 Page 24
C Programming for Problem Solving 18CPS23
7. Space Mouse 8.Digital Stills Camera
9. Magnetic Ink Character 10.OpticalMarkReader
Recognition (MICR) (OMR)
11. Image Scanner 12. Bar Codes
13. Magnetic Reader 14. Smart Cards
15. Voice Data Entry 16. Sound Capture
17. Video Capture
The Keyboard is the standard data input and operator control device for a computer. It consists
of the standard QWERTY layout with a numeric keypad and additional function keys for control
purposes.
The Mouse is a popular input device. You move it across the desk and its movement is shown on
the screen by a marker known as a 'cursor'. You will need to click the buttons at the top of the
mouse to select an option.
Track ball looks like a mouse, as the roller is on the top with selection buttons on the side. It is
also a pointing device used to move the cursor and works like a mouse. For moving the cursor in
a particular direction, the user spins the ball in that direction. It is sometimes considered better
than a mouse, because it requires little arm movement and less desktop space. It is generally used
with Portable computers.
Dept. of CSE, BNMIT 2018-19 Page 25
C Programming for Problem Solving 18CPS23
Magnetic Ink Character Recognition (MICR) is used to recognize the magnetically charged
characters, mainly found on bank cheques. The magnetically charged characters are written by
special ink called magnetic ink. MICR device reads the patterns of these characters and compares
them with special patterns stored in memory. Using MICR device, a large volume of cheques can be
processed in a day. MICR is widely used by the banking industry for the processing of cheques.
The joystick is a rotary lever. Similar to an aircraft's control stick, it enables you to move within
the screen's environment, and is widely used in the computer games industry.
A Digitising Tablet is a pointing device that facilitates the accurate input of drawings and
designs. A drawing can be placed directly on the tablet, and the user traces outlines or inputs
coordinate positions with a hand-held stylus.
A Touch Sensitive Screen is a pointing device that enables the user to interact with the
computer by touching the screen. There are three types of Touch Screens: pressure-sensitive,
capacitive surface and light beam.
A Light Pen is a pointing device shaped like a pen and is connected to a VDU. The tip of the
light pen contains a light-sensitive element which, when placed against the screen, detects the
light from the screen enabling the computer to identify the location of the pen on the screen.
Light pens have the advantage of 'drawing' directly onto the screen, but this can become
uncomfortable, and they are not as accurate as digitising tablets.
The Space mouse is different from a normal mouse as it has an X axis, a Y axis and a Z axis. It
can be used for developing and moving around 3-D environments.
Digital Stills Cameras capture an image which is stored in memory within the camera. When
the memory is full it can be erased and further images captured. The digital images can then be
downloaded from the camera to a computer where they can be displayed, manipulated or printed.
Dept. of CSE, BNMIT 2018-19 Page 26
C Programming for Problem Solving 18CPS23
The Optical Mark Reader (OMR) can read information in the form of numbers or letters and
put it into the computer. The marks have to be precisely located as in multiple choice test papers.
Scanners allow information such as a photo or text to be input into a computer. Scanners are
usually either A4 size (flatbed), or hand-held to scan a much smaller area. If text is to be
scanned, you would use an Optical Character Recognition (OCR) program to recognise the
printed text and then convert it to a digital text file that can be accessed using a computer.
A Bar Code is a pattern printed in lines of differing thickness. The system gives fast and error-free
entry of information into the computer. You might have seen bar codes on goods in supermarkets, in
libraries and on magazines. Bar codes provide a quick method of recording the sale of items.
Card Reader: This input device reads a magnetic strip on a card. Handy for security reasons, it
provides quick identification of the card's owner. This method is used to run bank cash points or
to provide quick identification of people entering buildings.
Dept. of CSE, BNMIT 2018-19 Page 27
C Programming for Problem Solving 18CPS23
Smart Card: This input device stores data in a microprocessor embedded in the card. This
allows information, which can be updated, to be stored on the card. This method is used in
store cards which accumulate points for the purchaser, and to store phone numbers for
cellular phones.
OUTPUT DEVICES :
Output devices display information in a way that you can you can understand. The most
common output device is a monitor. It looks a lot a like a TV and houses the computer
screen. The monitor allows you to 'see' what you and the computer are doing together.
Brief of Output Device
Output devices are pieces of equipment that are used to get information or any other response
out from computer. These devices display information that has been held or generated within
a computer. Output devices display information in a way that you can understand. The most
common output device is a monitor.
Types of Output Device
Printing: Plotter, Printer
Sound : Speakers
Visual : Monitor
A Printer is another common part of a computer system. It takes what you see on the
computer screen and prints it on paper. There are two types of printers; Impact Printers and
Non-Impact Printers.
Dept. of CSE, BNMIT 2018-19 Page 28
C Programming for Problem Solving 18CPS23
Speakers are output devices that allow you to hear sound from your computer. Computer
speakers are just like stereo speakers. There are usually two of them and they come in various
sizes.
Dept. of CSE, BNMIT 2018-19 Page 29
C Programming for Problem Solving 18CPS23
Overview of C
C is a general-purpose, high-level language that was originally developed by Dennis M.
Ritchie to develop the UNIX operating system at Bell Labs. C was originally first
implemented on the DEC PDP-11 computer in 1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available
description of C, now known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application programs
have been written in C. C has now become a widely used professional language for various
reasons −
Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around the early 1970s.
The language was formalized in 1988 by the American National Standard Institute
(ANSI).
The UNIX OS was totally written in C.
Today C is the most widely used and popular System Programming Language.
Most of the state-of-the-art software have been implemented using C.
Today's most popular Linux OS and RDBMS MySQL have been written in C.
Why use C?
C was initially used for system development work, particularly the programs that make-up
the operating system. C was adopted as a system development language because it produces
code that runs nearly as fast as the code written in assembly language. Some examples of the
use of C might be −
Operating Systems
Dept. of CSE, BNMIT 2018-19 Page 30
C Programming for Problem Solving 18CPS23
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
Brief History of C
The C programming language is a structure oriented programming language,
developed at Bell Laboratories in 1972 by Dennis Ritchie.
C programming language features were derived from an earlier language called “B”
(Basic Combined Programming Language – BCPL)
C language was invented for implementing UNIX operating system.
In 1978, Dennis Ritchie and Brian Kernighan published the first edition
“The C Programming Language” and is commonly known as K&R C.
In 1983, the American National Standards Institute (ANSI) established a committee
to provide a modern, comprehensive definition of C. The resulting definition, the
ANSI standard, or “ANSI C”, was completed late 1988.
Many of C’s ideas & principles were derived from the earlier language B, thereby
naming this new language “C”.
Dept. of CSE, BNMIT 2018-19 Page 31
C Programming for Problem Solving 18CPS23
Taxonomy of C Language
CHARECTERESTICS OF A C PROGRAM
Middle level language.
High Level Middle Level Low Level
High level languages Middle level languages don’t Low level languages
provide almost everything provide all the built-in functions provides nothing
that the programmer might found in high level languages, other than access to
need to do as already built but provides all building blocks the machines basic
into the language that we need to produce the result instruction set
we want
Examples: C, C++ Assembler
Java, Python
C Programs
A C program can vary from 3 lines to millions of lines and it should be written into one or
more text files with extension ".c"; for example, hello.c. You can use "vi", "vim" or any
other text editor to write your C program into a file.
Basic structure of C program
The structure of a C program is a protocol (rules) to the programmer, which he has to follow
while writing a C program. The general basic structure of C program is shown in the figure
below.
Dept. of CSE, BNMIT 2018-19 Page 32
C Programming for Problem Solving 18CPS23
Hello World Example
A C program basically consists of the following parts −
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words "Hello World" −
Live Demo
Dept. of CSE, BNMIT 2018-19 Page 33
C Programming for Problem Solving 18CPS23
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Let us take a look at the various parts of the above program −
The first line of the program #include <stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
The next line int main() is the main function where the program execution begins.
The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
The next line return 0; terminates the main() function and returns the value 0.
Local Environment Setup
If you want to set up your environment for C programming language, you need the
following two software tools available on your computer, (a) Text Editor and (b) The C
Compiler.
Text Editor
Dept. of CSE, BNMIT 2018-19 Page 34
C Programming for Problem Solving 18CPS23
This will be used to type your program. Examples of few a editors include Windows
Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For example,
Notepad will be used on Windows, and vim or vi can be used on windows as well as on
Linux or UNIX.
The files you create with your editor are called the source files and they contain the program
source codes. The source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you
have enough experience to write a computer program, save it in a file, compile it and finally
execute it.
The C Compiler
The source code written in source file is the human readable source for your program. It
needs to be "compiled", into machine language so that your CPU can actually execute the
program as per the instructions given.
The compiler compiles the source codes into final executable programs. The most frequently
used and free available compiler is the GNU C/C++ compiler, otherwise you can have
compilers either from HP or Solaris if you have the respective operating systems.
The following section explains how to install GNU C/C++ compiler on various OS. We
keep mentioning C/C++ together because GNU gcc compiler works for both C and C++
programming languages.
Installation on UNIX/Linux
If you are using Linux or UNIX, then check whether GCC is installed on your system by
entering the following command from the command line −
$ gcc -v
If you have GNU compiler installed on your machine, then it should print a message as
follows −
Using built-in specs.
Target: i386-redhat-linux
Dept. of CSE, BNMIT 2018-19 Page 35
C Programming for Problem Solving 18CPS23
Configured with: ../configure --prefix=/usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If GCC is not installed, then you will have to install it yourself using the detailed
instructions available at https://gcc.gnu.org/install/
This tutorial has been written based on Linux and all the given examples have been
compiled on the Cent OS flavor of the Linux system.
Executing a C program
Let us see how to save the source code in a file, and how to compile and run it. Following
are the simple steps −
Open a text editor and add the above-mentioned code.
Save the file as hello.c
Open a command prompt and go to the directory where you have saved the file.
Type gcc hello.c and press enter to compile your code.
If there are no errors in your code, the command prompt will take you to the next line
and would generate a.out executable file.
Now, type a.out to execute your program.
You will see the output "Hello World" printed on the screen.
$ gcc hello.c
$ ./a.out
Hello, World!
Make sure the gcc compiler is in your path and that you are running it in the directory
containing the source file hello.c.
You have seen the basic structure of a C program, so it will be easy to understand other
basic building blocks of the C programming language.
Dept. of CSE, BNMIT 2018-19 Page 36
C Programming for Problem Solving 18CPS23
Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a
constant, a string literal, or a symbol. For example, the following C statement consists of
five tokens −
printf("Hello, World! \n");
The individual tokens are −
printf
(
"Hello, World! \n"
)
;
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
Given below are two different statements −
printf("Hello, World! \n");
return 0;
Comments
Comments are like helping text in your C program and they are ignored by the compiler.
They start with /* and terminate with the characters */ as shown below −
/* my first program in C */
You cannot have comments within comments and they do not occur within a string or
character literals.
Dept. of CSE, BNMIT 2018-19 Page 37
C Programming for Problem Solving 18CPS23
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item.
An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more
letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-
sensitive programming language. Thus, Manpowerand manpower are two different
identifiers in C. Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
Keywords
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names.
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a
C compiler totally ignores it.
Dept. of CSE, BNMIT 2018-19 Page 38
C Programming for Problem Solving 18CPS23
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to
identify where one element in a statement, such as int, ends and the next element begins.
Therefore, in the following statement −
int age;
there must be at least one whitespace character (usually a space) between int and age for the
compiler to be able to distinguish them. On the other hand, in the following statement −
fruit = apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit and =, or between = and apples,
although you are free to include some if you wish to increase readability.
FILES USED IN A C PROGRAM
Source File- This file contains the source code of the program. The file extension of
any c file is .c. The file contains C source code that defines the main function &
maybe other functions.
Header File- A header file is a file with extension .h which contains the C function
declarations and macro definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension .o,
meaning relocatable format machine code that is usually not directly executable.
Object files are produced by an assembler, compiler, or other language translator,
and used as input to the linker, which in turn typically generates an executable or
library by combining parts of object files.
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.
Dept. of CSE, BNMIT 2018-19 Page 39
C Programming for Problem Solving 18CPS23
Dept. of CSE, BNMIT 2018-19 Page 40
C Programming for Problem Solving 18CPS23
ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the language.
Character Set
Dept. of CSE, BNMIT 2018-19 Page 41
C Programming for Problem Solving 18CPS23
Communicating with a computer involves speaking the language the computer understands.
In C, various characters have been given to communicate.
Character set in C consists of;
Types Character Set
Lower case a-z
Upper case A-Z
Digits 0-9
Special Character !@#$%^&*
White space Tab or new lines or space
Constant, variable and data types
Identifier
In the programming language C, an identifier is a combination of alphanumeric characters,
the first being a letter of the alphabet or an underline, and the remaining being any letter of
the alphabet, any numeric digit, or the underline.
Two rules must be kept in mind when naming identifiers.
1. The case of alphabetic characters is significant. Using "INDEX" for a variable is
not the same as using "index" and neither of them is the same as using "InDeX" for
a variable. All three refer to different variables.
Dept. of CSE, BNMIT 2018-19 Page 42
C Programming for Problem Solving 18CPS23
2. As C is defined, up to 32 significant characters can be used and will be considered
significant by most compilers. If more than 32 are used, they will be ignored by the
compiler.
Data Type
In the C programming language, data types refer to a domain of allowed values & the
operations that can be performed on those values. The type of a variable determines how
much space it occupies in storage and how the bit pattern stored is interpreted. There are 4
fundamental data types in C, which are- char, int, float &, double. Char is used to store any
single character; int is used to store any integer value, float is used to store any single
precision floating point number & double is used to store any double precision floating
point number. We can use 2 qualifiers with these basic types to get more types.
There are 2 types of qualifiers-
Sign qualifier- signed & unsigned
Size qualifier- short & long
The data types in C can be classified as follows:
Type Storage size Value range
char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
Dept. of CSE, BNMIT 2018-19 Page 43
C Programming for Problem Solving 18CPS23
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Type Storage size Value range Precision
float 4 bytes 1.2E-38 to 3.4E+38 6 decimal places
double 8 bytes 2.3E-308 to 1.7E+308 15 decimal places
long double 10 bytes 3.4E-4932 to 1.1E+4932 19 decimal places
Constants
A constant is an entity that doesn’t change whereas a variable is an entity that may change.
C constants can be divided into two major categories:
Primary Constants
Secondary Constants
Dept. of CSE, BNMIT 2018-19 Page 44
C Programming for Problem Solving 18CPS23
Here our only focus is on primary constant. For constructing these different types of
constants certain rules have been laid down.
Rules for Constructing Integer Constants:
An integer constant must have at least one digit.
a) It must not have a decimal point.
b) It can be either positive or negative.
c) If no sign precedes an integer constant it is assumed to be positive.
d) No commas or blanks are allowed within an integer constant.
e) The allowable range for integer constants is -32768to 32767.
Dept. of CSE, BNMIT 2018-19 Page 45
C Programming for Problem Solving 18CPS23
Real constants are often called Floating Point constants. The real constants could be written
in two forms—Fractional form and Exponential form.
Rules for constructing real constants expressed in fractional form:
a) A real constant must have at least one digit.
b) It must have a decimal point.
c) It could be either positive or negative.
d) Default sign is positive.
e) No commas or blanks are allowed within a real
constant. Ex. +325.34, 426.0, -32.76, -48.5792
The mantissa part and the exponential part should be separated by a letter e.
The mantissa part may have a positive or negative sign.
Default sign of mantissa part is positive.
The exponent must have at least one digit, which must be a positive or negative
integer. Default sign is positive.
Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.
Dept. of CSE, BNMIT 2018-19 Page 46
C Programming for Problem Solving 18CPS23
A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas.
The maximum length of a character constant can be 1 character.
Ex.: ‘M’, ‘6’, ‘+’
Variables
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in C has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It
must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because C is case-sensitive. Based on the basic types explained in the previous chapter, there
will be the following basic variable types
Dept. of CSE, BNMIT 2018-19 Page 47
C Programming for Problem Solving 18CPS23
Sr.No. Type & Description
1 char
Typically a single octet(one byte). This is an integer type.
2 int
The most natural size of integer for the machine.
3 float
A single-precision floating point value.
4 double
A double-precision floating point value.
5 void
Represents the absence of type.
C programming language also allows to define various other types of variables, which we
will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc.
For this chapter, let us study only basic variable types.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or
any user-defined object; and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
Dept. of CSE, BNMIT 2018-19 Page 48
C Programming for Problem Solving 18CPS23
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler
to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Dept. of CSE, BNMIT 2018-19 Page 49
C Programming for Problem Solving 18CPS23
Declaring Variables:
There are two places where you can declare a variable:
After the opening brace of a block of code (usually at the top of a function)
Before a function name (such as before main() in the program) Consider various
examples:
Suppose you had to keep track of a person's first, middle, and last initials.
Because an initial is obviously a character, it would be prudent to declare three
character variables to hold the three initials. In C, you could do that with the
following statement:
1. main()
{
char first, middle, last;
/ Rest of program follows
}
2. main()
{ char
first;
char
middle;
char last;
Dept. of CSE, BNMIT 2018-19 Page 50
C Programming for Problem Solving 18CPS23
// Rest of program follows
}
Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage
value. If we want we can assign some initial value to the variables during the
declaration itself. This is called initialization of the variable.
Eg- int pageno=10;
char grade=’A’;
float salary= 20000.50;
Types of operators and expressions,
Arithmetic operators:
C provides all the basic arithmetic operators. The operators +,-,* and / all work the same way
as
they do in other languages. These can operate on any built-in data type allowed in C. The
unary
minus operator, in effect, multiplies its single operand by -1. Therefore, a number preceded
by a
minus sign changes its sign.
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division
Dept. of CSE, BNMIT 2018-19 Page 51
C Programming for Problem Solving 18CPS23
Integer division truncates any fractional part. The modulo division produces the remainder of
an
integer division.
Examples are:
a-b
a+b
a*b
a/b
a%b
-a * b
Here a and b are variables and are known as operands. The modulo divison operator %
cannot be used on floating point data.
Arithmetic expressions:
An arithmetic expression is a combination of variables, constants and operators arranged as
per the syntax of the language. Expressions are evaluated using an assignment statement of
the form
Variable=expression;
The table below shows the algebraic expression and C language expression
Dept. of CSE, BNMIT 2018-19 Page 52
C Programming for Problem Solving 18CPS23
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and the result then replaces the precious value of the variable on the left-hand
side. All variables used in the expression must be assigned values before evaluation is
attempted.
x = a * b -c ;
y=b/c*a;
z = a -b / c + d ;
The blank space around an operator is optional and adds only to improve readability. When
these
statements are used in a program, the variables a ,b ,c and d must be defined before they are
used in the expressions.
Modes of expression:
There are three different modes of expression.
1. Integer Arithmetic
2. Real Arithmetic
3. Mixed-mode Arithmetic
Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression, and the operation is called integer arithmetic. This
mode of expression always yields an integer value. The largest integer value depends on the
machine, as pointed out earlier
Example:
If a and b are integers then for a = 1 4 and b = 4
We have the following results:
a - b=10
a + b = 18
a * b = 56
Dept. of CSE, BNMIT 2018-19 Page 53
C Programming for Problem Solving 18CPS23
a / b=3
a %b=2
During integer division, if both the operands are of the same sign, the result is truncated
towards zero. If one of them is negative, is,
6 / 7 =0
the direction of truncation is implementation dependent. That and -6/-7=0
but -6/7 may be zero -1 (Machine dependent)
Similarly, during modulo division , the sign of the result is always the sign of the first
operand(the dividend). That is
-14 % 3 =-2
-14 % -3= -2
14 % -3=2
Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real
operand may assume values either in decimal or exponential notation. Since floating point
values are rounded to the number of significant digits permissible, the final value is an
approximation of the correct result. If x, y, and z are floats, then we will have:
x=6.0/7.0=0.857143
y= 1.0/3.0 =0.333333
z= -2.0/3.0= -0.666667
The operator % cannot be used with real operands.
Mixed- mode Arithmetic
When one of the operands is real and the other is integer, the expression is called a mixed-
mode arithmetic expression. If either operand is of the real t ype, then only the real operation
is performed and the result is always a real number.
Thus
15/10.0=1.5
where as
Dept. of CSE, BNMIT 2018-19 Page 54
C Programming for Problem Solving 18CPS23
15/10=1
Arithmetic operators precedence: In a program the value of any expression is calculated by
executing one arithmetic operation at a time. The order in which the arithmetic operations are
executed in an expression is based on the rules of precedence of operators.
The precedence of operators is :
Unary (-) FIRST
Multiplication(*) SECOND
Division(/) and (%)
Addition(+) and Subtraction(-) LAST
For example, in the integer expression –a *b/c+d the unary- is done first, the result –a is
multiplied by b, the product is divided by c(integer division) and d is added to it. The answer
is thus:
-a b / c + d
All the expressions are evaluated from left to right. All the unary negations are done first.
After completing this the expression is scanned from left to right; now all *, / and %
operations are executed in the order of their appearance. Finally all the additions and
subtractions are done starting from the left of the expression..
For example, in the expression:
z=a + b* c
Initially b*c is evaluated and then the resultant is added with a. Suppose if want to add a with
b first, then it should be enclosed with parenthesis , is shown below
z = (a + b ) * c
Use of parentheses:
Parentheses are used if the order of operations governed by the precedence rules are to be
overridden. In the expression with a single pair of parentheses the expression inside the
parentheses is evaluated FIRST. Within the parentheses the evaluation is governed by the
precedence rules.
For example, in the expression:
a * b/(c+d * k/m+k)+a
the expression within the parentheses is evaluated first giving:
c+ d k / m + k
Dept. of CSE, BNMIT 2018-19 Page 55
C Programming for Problem Solving 18CPS23
After this the expression is evaluated from left to right using again the rules of precedence
giving
ab/c+dk/m+k +a
If an expression has many pairs of parentheses then the expression in the innermost pair is
evaluated first, the next innermost and so on till all parentheses are removed. After this the
operator precedence rules are used in evaluating the rest of the expression.
((x * y)+z/(n*p+j)+x)/y+z
xy,np+j will be evaluated first.
In the next scan
xy+z/np+j +x
Will be evaluated. In the final scan the expression evaluated would be:
(xy+ z/np+j+x)/y +z
Increment and Decrement operators:
The increment operator ++ and decrement operator – are unary operators with the same
precedence as the unary -, and they all associate from right to left. Both ++ and – can be
applied to variables, but no to constants or expressions. They can occur in either prefix or
postfix position, with possibly different effects occurring. These are usually used with integer
data type.
The general syntax is:
++variable|--variable| variable++| variable—
Some examples are
++count
-kk
index++
unit_one--
We use the increment and decrement statements in for and while extensively.
Consider the following example
m=5;
y=++m;
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statements as
m=5;
Dept. of CSE, BNMIT 2018-19 Page 56
C Programming for Problem Solving 18CPS23
y =m++;
then the value of y would be 5 and m would 6. A prefix operator first adds to 1 to the operand
and then the result is assigned to the variable on left. On the other hand, a postfix operator
first assigns the value to the variable on left and then increments the operand. Similar is the
case, when we use ++(or--) in the subscripted variables. That is, the statement
a[i++]=10;
is equivalent to
a[i]=10;
i=i+1;
The increment and decrement operators can be used in complex statements. Example m = n +
+ -j + 1 0 ;
Old value of n is used in evaluating the expression. n is incremented after the evaluation.
Relational operators:
We often compare two quantities and depending on their relation, to take certain decisions.
For example, we may compare the age of two persons, or the price of two items, and so on.
These comparisons can be done with the help of relational operators. C supports six relational
operators in all. These operators and their meanings are shown below
Relational Operators
< is less than
> i s g re a t e r t h a n
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
Dept. of CSE, BNMIT 2018-19 Page 57
C Programming for Problem Solving 18CPS23
A simple relational expression contains only one relational operator and has the following
form:
ae- 1 relational operator ae-2.
ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or
combination of them.
Given below are some examples of simple relational expressions and their values:
4.5<=10 TRUE
4.5<10 FALSE
-35>=0 FALSE
10<7+5 TRUE
a+ b = =c+ d TRUE only if the sum of values of a and b is equal to the sum of values of c
and d.
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.
Logical operators:
In addition to the relational operators . C has the following three logical operators.
&& logical AND
|| logical OR
! logical NOT
The logical operators && and || are used when we want to test more than one condition and
make decisions.
a>b && x == 10
Dept. of CSE, BNMIT 2018-19 Page 58
C Programming for Problem Solving 18CPS23
An expression of this kind which combines two or more relational expression is termed as a
logical expression or a compound relational expression. Like the simple relational
expressions , a logical expression also yields a value of one or zero, according to the truth
table shown below.
The logical expression given above is true only if a>b is true and x==10 is true. If either (or
both) of them are false, the expression is false.
Some examples of the usage of logical expressions are:
If(age>55 && salary <1000)
If (number<0 || number>100)
Relational and logical expressions:
We have seen that float or integer quantities may be connected by relational operators to
yield an answer which is true of false.
For example the expression,
M a rk s > = 6 0
Would have an answer true if marks is greater than or equal to 60 and false if marks is less
than 60.
The result of the comparison (marks>=60) is called a logical quantity. C provides a facility to
combine such logical quantities by logical operators to logical expressions. These logical
expressions are useful in translating intricate problem statements.
Example :
A university has the following rules for a student to qualify for a degree with Physics as the
main subject and Mathematics as the subsidiary subject:
He should get 50 percent or more in Physics and 40 percent or more in Mathematics.
Dept. of CSE, BNMIT 2018-19 Page 59
C Programming for Problem Solving 18CPS23
If he gets less than 50 percent in Ph ysics he should get 50 percent or more in Mathematics.
He
should get atleast 40 percent in Physics.
If he gets less than 40 percent in Mathematics and 60 percent or more in Physics he is
allowed to reappear in an examination in Mathematics to qualify.
In all the other cases he is declared to have failed.
A Decision Table for Examination Results
/*This program implements above rules*/
include<stdio.h>
m a i n ()
{
unsigned int roll_no, physics_marks, chem_marks;
while(scanf(“%d %d %d”, &roll_no,&physics_marks, &chem_marks)!=EOF)
{
If(((c h e m _ m a rk s > = 5 0 &&(physics_marks>=35))||((c h e m _ m a rk s > = 4 0 ))
& & (p h y s i c s _ m a rk s > = 5 0 )))
printf(“%d %d %d Pass\n”, roll_no, chem_marks, physics_marks);
else if (( chem_marks>=60)) && physics_marks<35))
printf(“%d %d %d Repeat Physics\n”, roll_no,physics_marks,chem_marks);
else
Dept. of CSE, BNMIT 2018-19 Page 60
C Programming for Problem Solving 18CPS23
printf(“%d %d %d Failed \n”, roll_no, physics _marks, chem_marks);
}
}/*End while*/
}/*End main*/
Precedence of relational operators and logical operators:
Example:
(a > b * 5 ) & & (x < y + 6 )
In the above example, the expressions within the parentheses are evaluated first. The
arithmetic operations are carried out before the relational operations. Thus b*5 is calculated
and after that a is compared with it. Similarly y+6 is evaluated first and then x is compared
with it . In general within parentheses:
The unary operations, namely, -,++,--,! (logical not) are performed first.
Arithmetic operations are performed next as per their precedence.
After that the relational operations in each sub expressions are performed, each sub
expression will be a zero or non _ zero. If it is zero it is taken as false else it is taken as true.
These logical values are now operated on by the logical operators.
Next the logical operation && is performed next.
Lastly the evaluated expression is assigned to a variable name as per the assignment operator.
The conditional operators:
An operator called ternary operator pair “? :” is available in C to construct conditional
expressions of the form.
exp1? exp2: exp3;
where exp1,exp2, and exp3 are expressions.
The operator ?; works as follows: exp1 is evaluated first. If it is nonzero(true), then the
expression exp2 is evaluated and becomes the value of the expression. If exp1 is false, exp3
is evaluated and its value becomes the value of the expression. Note that only one of the
expressions(either exp2 or exp3) is evaluated.
For example, consider the following statements
x=3;
y=15;
z = (x > y )? x : y ;
Dept. of CSE, BNMIT 2018-19 Page 61
C Programming for Problem Solving 18CPS23
In this example, z will be assigned the value of b. This can be achieved using the if..else
statements as follows:
If (x>y)
z=x;
else
z=b;
Bitwise operators:
C has a distinction of supporting special operators known as bitwise operators for
manipulation of data at bit level. These operators are used for testing the bits, or shifting them
right or left.
Bitwise operators may not be applied to float or double. where the filename is the name
containing the required definitions or functions. At this point, the preprocessor inserts the
entire contents of the filename into the source code of the program. When the filename is
included within the double quotation marks, the search for the file is made first in the
directory and then in the standard directories.
The Comma Operator
C has some special operators. The comma operator is one among them. This operator can be
used to link the related expressions together. A comma-linked list of expressions are
Dept. of CSE, BNMIT 2018-19 Page 62
C Programming for Problem Solving 18CPS23
evaluated left to right and the value of right-most expression is the value of the combined
expression.
For example, the statement
Value=(a=2, b=6 ,a+b);
First assigns the value 2 to a, then assigns 6 to b, and finally assigns 8(i.e 2+6) to value. The
comma operator has the lowest precedence of all operators, hence the parentheses are
necessary.
Some examples are given below:
In for loops:
for(a = 1 , b = 1 0 ; a < = b ; a + + , b + + )
In while loops:
while(c=getchar(), c!=’10’)
Exchanging values:
t=x, x=y, y=t;
The precedence of operators among themselves and across all the set of operators:
Each operator in C has a precedence associated with it. This precedence is used to determine
how an expression involving more than one operator is evaluated. The operator at the higher
level of precedence are evaluated first
Dept. of CSE, BNMIT 2018-19 Page 63
C Programming for Problem Solving 18CPS23
The associatively of operators:
Dept. of CSE, BNMIT 2018-19 Page 64
C Programming for Problem Solving 18CPS23
The operators of the same precedence are evaluated either from left to right or from right to
left depending on the level. This is known as the associatively property of an operator.
The table below shows the associatively of the operators:
Evaluation of expressions involving all the above type of operators:
The following expression includes operators from six different precedence groups.
Consider variables x, y , z as integer variables.
Z+=(x0>0 && x<=10) ? ++x : x/y;
The statement begins by evaluating the complex expression
(x>0 && x<=10)
If this expression is true, the expression ++x is evaluated. Other wise, the a/b is evaluated.
Dept. of CSE, BNMIT 2018-19 Page 65
C Programming for Problem Solving 18CPS23
Finally, the assignment operation(+=) is carried out, causing the value of c to be increased by
the value of the conditional expression. If for example x, y, and z have the values 1,2,3
respectively, then the value of the conditional expression will be 2(because the expression +
+a will be evaluated), and the value of z will increase to 5(z=3+2). On the other hand, if x,y
and z have the values 50,10,20 respectively, then the value of the conditional expression will
be 5(because the expression x/y will be evaluated) and the value of z will increase to
25(z=20+5).
Generic Programming Examples
1. Sample program illustrating each data type
#include < stdio.h >
void main()
{
int sum;
float money;
char letter;
double pi;
sum = 10; /* assign integer value */
money = 2.21; /* assign float value */
letter = 'A'; /* assign character value */
pi = 2.01E6; /* assign a double value */
printf("value of sum = %d\n", sum );
printf("value of money = %f\n", money );
printf("value of letter = %c\n", letter );
printf("value of pi = %e\n", pi );
}
Sample program output
Dept. of CSE, BNMIT 2018-19 Page 66
C Programming for Problem Solving 18CPS23
value of sum = 10
value of money = 2.210000
value of letter = A
value of pi = 2.010000e+06
Dept. of CSE, BNMIT 2018-19 Page 67
C Programming for Problem Solving 18CPS23
printf("Number is %d\n", number );
}
Dept. of CSE, BNMIT 2018-19 Page 68