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

module 1 pop c

The document provides an introduction to the principles of programming using C, covering the basics of computer systems, their characteristics, and the history of computer generations. It details the evolution from vacuum tubes to ultra-large scale integration technology, highlighting key features and examples of each generation. Additionally, it classifies computers based on size and speed, explaining the applications of computers in various fields such as home, medical, and entertainment.

Uploaded by

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

module 1 pop c

The document provides an introduction to the principles of programming using C, covering the basics of computer systems, their characteristics, and the history of computer generations. It details the evolution from vacuum tubes to ultra-large scale integration technology, highlighting key features and examples of each generation. Additionally, it classifies computers based on size and speed, explaining the applications of computers in various fields such as home, medical, and entertainment.

Uploaded by

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

BPOPS103/203

Principles of Programming Using C BPOPS103


Module-1 Introduction to C

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

1.2 Characteristics of the Computer System

The characteristics of the computer system are as follows −

Economical

Speed
A computer works with much higher speed and accuracy compared to humans while
performing mathematical calculations. Computers can process millions (1,000,000) of
instructions per second. The time taken by computers for their operations is microseconds and
nanoseconds.
Accuracy
Computers perform calculations with 100% accuracy. Errors may occur due to data
inconsistency or inaccuracy.

Prof. GEETHA R Page 1


22POP13/23

Diligence
A computer can perform millions of tasks or calculations with the same consistency and
accuracy. It doesn’t feel any fatigue or lack of concentration. Its memory also makes it superior
to that of human beings
Versatility
Versatility refers to the capability of a computer to perform different kinds of works with same
accuracy and efficiency.
Reliability
A computer is reliable as it gives consistent result for similar set of data i.e., if we give same
set of input any number of times, we will get the same result.
Automation
Computer performs all the tasks automatically i.e. it performs tasks without manual
intervention.
Memory
A computer has built-in memory called primary memory where it stores data.
Secondary storage are removable devices such as CDs, pen drives, etc., which are also used to
store data.
No IQ:
Computer is a dumb machine and it cannot do any work without
instruction from the user. It performs the instructions at tremendous speed and with accuracy.
It is you to decide what you want to do and in what sequence. So a computer
Storage
The Computer has an in-built memory where it can store a large amount of data. You can also
store data in secondary storage devices such as floppies, which can be
kept outside your computer and can be carried to other computers.
Economical
Using computers also reduces manpower requirements and leads to an elegant and efficient
way of performing various tasks. Hence, computers save time, energy, and money. When
compared to other systems, computers can do more work in lesser time.

Prof. GEETHA R Page 2


22POP13/23

1.4 History of Computers

Computer Generations
The computer of each generation is smaller, faster and more powerful than preceding
generation. There are five computer generations.

Generation Based on Other Features

First(1942 to 1955) Vacuum tubes Magnetic drums for memory

Second(1955 to 1964) Transistors Magnetic cores, disks, punched cards and


printouts
Third(1965 to 1975) Integrated circuits(ICs) Keyboard, monitor and operating system

Fourth(1975– 1989 ) Microprocessors Networking

Fifth(1989-present) ULSI Nano Mainly unclear


technology.

First Generation: The vacuum tubes were used for computation. Magnetic drums were used
for memory requirements. It consumed lot of space, power and generated lot of power. ENIAC
(Electronic Numerical Integrator and Computer) used 18000 vacuum tubes, 1800 acquired sq.
ft. room space and consumed 180KW of power. The machine level language (0s and 1s) was
used. Punched cards were used for input and Paper for output. They were used for scientific
work.

Examples: ENIAC, EDVAC, EDSAC, UNIVAC I, IBM 701


MainFeatures:
➢ Vacuum tube technology
➢ Unreliable and Not portable
➢ Supported machine language only
➢ Consumed lot of electricity Hence Cost is high
➢ Huge size and Generate lot of heat
➢ Slow Input/Output device

Prof. GEETHA R Page 3


22POP13/23

Second Generation: The transistors was the most important component which replaced
vacuum tubes. Magnetic cores were used for memory. It were more reliable than first
generation computer. The assembly or symbolic language was used. The input and output
mechanism remained same. The stored program concept was introduced which stores both
data and program.

Examples: Honeywell 400, IBM 7030, CDC 1604, UNIVAC LARC


Main Features:
➢ Transistor technology
➢ Support machine language, assembly language
➢ Reliable, Smaller in size, Generate less heat, consumed less electricity, fast compared to
First generation.

Prof. GEETHA R Page 4


22POP13/23

Third Generation: The Integrated circuits(IC) was the most important component. The
transistors, diodes, resistors, capacitors were integrated on a single chip. The high-level
language was used like BASIC,C, C++ and JAVA. Memory capacity increased and magnetic
hard disk was used for secondary generation.The third generation computers also had OS and
computer could rum programs invoked by multi users.
Examples: IBM 360/370, PDP-8, PADP-11, CDC6600
Main Features:
➢ IC used
➢ Support high level programming languages like FORTRAN, COBAL, PASCAL, BASIC,
ALGOL C, C++ and Java.
➢ More reliable, smaller size, generate less heat, consumed less electricity, fast compared
to Second generation.
➢ High cost

Fourth Generation: The Microprocessor was the most important component. With the help
of using IC’s with LSI (Large Scale Integration) and later with VLSI (Very Large Scale

Prof. GEETHA R Page 5


22POP13/23
Integration) the entire CPU is on a single chip. OS have moved from MSDOS to GUI
(Graphical User Interface) like windows. The networking technology has also been improved.
The size was reduced and the speed was increased. Microcomputers came into existence. Use
of personal computers became widespread. High speed computer networks in the form of
LANs, WANs, and MANs started growing.

Examples IBM PC, Apple II, TRS-80, VAX 9000, CRAY1, CRAY-2, CRAY-X/MP
Main Features:
➢ VLSI Technology
➢ Very cheap, Portable, reliable, small size
➢ Networking and Internet

Fifth Generation: Manufactured using IC’s with ULSI (Ultra large scale integrated) Artificial
Intelligence and use of natural languages are the main features of this generations. These
systems are expected to interact with users in natural language. Speech recognition and speech
output should also be possible. Computers must be able to perform parallel processing. The
quad-core and octa-core was also introduced. Neural networks and expert systems have been
developed.

Examples IBM notebooks, Pentium PCs, SUM workstations, IBM SP/2, Param
supercomputer

Prof. GEETHA R Page 6


22POP13/23

Main Features:

➢ ULSI (Ultra Large Scale Integrated circuit) technology


➢ Development of Artificial Intelligence

➢ Perform parallel processing


➢ User friendly interface with multimedia features

➢ Available at very powerful and compact computers at cheaper rate

1.5 Classification of Computers

Classification of computer based on size and speed


➢ Supercomputers
➢ Mainframes
➢ Minicomputers
➢ Microcomputers

Prof. GEETHA R Page 7


22POP13/23

Supercomputers: Among the four categories, the supercomputer is the fastest, most
powerful, and most expensive computer. Supercomputers were first developed in the 1980s to
process large amounts of data and to solve complex scientific problems. Supercomputers use
parallel processing technology and can perform more than one trillion calculations in a
second. Speeds are measured in FLOPS (floating point operations persecond). The
fastest operates at 34 petaflops.
Such computers are mainly used for weather forecasting, nuclear energy research, aircraft
design, automotive design, online banking, controlling industrial units, etc. Some examples
of supercomputers are CRAY-1, CRAY-2, Control Data CYBER 205, and ETA A-10.
Mainframes: Mainframe computers are large-scale computers (but smaller than
supercomputers). These are very expensive and need a very large clean room with air
conditioning, thereby making them very costly to deploy. The processor speed is measuredin
MIPS (Million instructions per second). As with supercomputers, mainframes can also
support multiple processors. For example, the IBM S/390 mainframe can support 50,000
users at the same time. Users can access mainframes by either using terminals or via PCs.
It is used to handle data, applications related to organization and online transactions in banks,
financial institutions and large corporations.
The two types of terminals that can be used with mainframe systems are as follows:
Dumb Terminals
Dumb terminals consist of only a monitor and a keyboard (or mouse). They do not have
their own CPU and memory and use the mainframe system’s CPU and storage devices.
Intelligent Terminals
In contrast to dumb terminals, intelligent terminals have their own processor and thus can
perform some processing operations. However, just like the dumb terminals, they do not have
their own storage space. Usually, PCs are used as intelligent terminals to facilitate data access
and other services from the mainframe system.
Minicomputers/Midrange computers: As the name suggests, minicomputers are smaller,
cheaper, and slower than mainframes. They are called minicomputers because they were the
smallest computer of their times. Also known as midrange computers , the capabilities of
minicomputers fall between mainframe and personal computers.
It was introduced by DEC (Digital Equipment Corporation). They can serve hundreds of
users and are small enough to partially occupy a room. They are used in smaller organizations
or a department of a large one. They are not affordable to be used in home.

Prof. GEETHA R Page 8


22POP13/23

Microcomputers: Microcomputers, commonly known as PCs, are very small and cheap. The
first microcomputer was designed by IBM in 1981 and was named IBM-PC. Later on, many
computer hardware companies copied this design and termed their microcomputers as PC-
compatible, which refers to any PC that is based on the original IBM PC design. Another type
of popular PC is designed by Apple. PCs designed by IBM and other PC-compatible
computers have a different architecture from that of Apple computers. Moreover, PCs and
PC-compatible computers commonly use the Windows operating system, while Apple
computers use the Macintosh operating system (MacOS). PCs can be classified into the
following
Desktop PCs
A desktop PC is the most popular model of PCs. The system unit of the desktop PC can be
placed flat on a desk or table. It is widely used in homes and offices.
Laptops
Laptops are small microcomputers that can easily fit inside a briefcase. They are very and
easily be carried from one place to another. They may also be placed on the user’s lap (thus
the name). The memory and storage capacity of a laptop is almost equivalent to that of a
desktop computer. As with desktop computers, laptops also have hard disk drives, USB
drives, etc. For input, laptops have a built-in keyboard and a trackball/touchpad, which is
used as a pointing device (as a mouse is used for a desktop PC).
Workstations
Workstations are single-user computers that have the same features as PCs, but their
processing speed matches that of a minicomputer or mainframe computer. Workstation
computers have advanced processors, more RAM and storage capacity than PCs. Therefore,
they are more expensive and powerful than a normal desktop computer.
Network Computers
Network computers have less processing power, memory, and storage than a desktop
computer. These are specially designed to be used as terminals in a networked environment.
For example, some network computers are specifically designed to access data stored on a
network (including the Internet and intranet).
Handheld Computers
These computers are called handheld computers because they can fit in one hand,
while users can use the other hand to operate them. Handheld computers are very small in
size, and hence they have small-sized screens and keyboards. These computers are

Prof. GEETHA R Page 9


22POP13/23

preferred by business travellers and mobile employees whose jobs require them to move
from place to place. Some examples of handheld computers are as follows:
• Smartphones
• Tablet PCs
Smartphones
These days, cellular phones are web-enabled telephones. Such phones are also known
as smartphones because, in addition to basic phone capabilities, they also facilitate the
users to access the Internet and send e-mails, edit Word documents, generate an Excel
sheet, create a presentation, and lots more. Smartphones run an advanced mobile
operating system that enables it to run various applications. The four major mobile
operating systems are iOS, Android, BlackBerry OS, and Windows Mobile. Smartphones
also have a CPU, more storage space, more memory, and a larger screen than a regular
cell phone.
Tablet PCs
A tablet PC is a computing device that is smaller than a laptop, but bigger than a
smartphone. Features such as user-friendly interface, portability, and touch screen have
made them very popular in the last few years. These days, a wide range of high-
performance tablets are available in the market. While all of them look similar from
outside, they may differ in features such as operating system, speed of data connectivity,
camera specifications, size of the screen, processing power, battery life, and storage
capability.

Prof. GEETHA R Page 10


22POP13/23

1.6 BITS, BYTES AND WORDS


➢ Computer can understand only two states: 0 and 1.
➢ A digit can have only 2 states or values known as a binary digit, abbreviated as bit(b).
➢ The name nibble was coined to represent four bits.
➢ The name byte (B) was coined to represent eight bits.
➢ The byte is the standard unit of measurement of computer memory, data storage and
transmission speed.
➢ The CPU handles memory data in larger units, called words and it is usually even
multiple of bytes (two bytes, four bytes etc.).
➢ When referred to a computer it has 32-bit (4 bytes) machine i.e., size of word is 32 bits.

Unit Equivalent to Remarks


1 kilobyte (KB) 1024 bytes Space used by 10 lines of text
1 megabyte (MB) 1024 kilobytes Memory of the earliest PCs
1 gigabyte (GB) 1024 megabytes Storage capacity of a CD-ROM
1 terabyte (TB) 1024 gigabytes Capacity of today’s hard disks
1 petabyte (PB) 1024 terabytes Space used for rendering of film Avatar

1.7Applications of Computers
Computers play a role in every field of life. They are used in homes, business, educational
institutions, research organizations, medical field, government offices, entertainment, Word
Processing, Internet, Digital Video or Audio composition ,Desktop Publishing ,e-business,
Business to consumer, Business to Business, consumer to consumer, Bio-informatics Health
Care etc.
➢ Home
Computers are used at homes for several purposes like online bill payment, watching
movies or shows at home, home tutoring, social media access, playing games, internet
access, etc. They provide communication through electronic mail. They help to avail
work from home facility for corporate employees. Computers help the student
community to avail online educational support.
➢ Medical Field
Computers are used in hospitals to maintain a database of patients’ history, diagnosis,
X-rays, live monitoring of patients, etc. Surgeons nowadays use robotic surgical devices

Prof. GEETHA R Page 11


22POP13/23
to perform delicate operations, and conduct surgeries remotely. Virtual reality
technologies are also used for training purposes. It also helps to monitor the fetus inside
the mother’s womb.
➢ Entertainment
Computers help to watch movies online, play games online; act as a virtual entertainer
in playing games, listening to music, etc. MIDI instruments greatly help people in the
entertainment industry in recording music with artificial instruments. Videos can be fed
from computers to full screen televisions. Photo editors are available with fabulous
features.

➢ Industry
Computers are used to perform several tasks in industries like managing inventory,
designing purpose, creating virtual sample products, interior designing, video
conferencing, etc. Online marketing has seen a great revolution in its ability to sell
various products to inaccessible corners like interior or rural areas. Stock markets have
seen phenomenal participation from different levels of people through the use of
computers.
➢ Education
Computers are used in education sector through online classes, online examinations,
referring e-books, online tutoring, etc. They help in increased use of audio-visual aids
in the education field.
➢ Government
In government sectors, computers are used in data processing, maintaining a database
of citizens and supporting a paperless environment. The country’s defense
organizations have greatly benefitted from computers in their use for missile
development, satellites, rocket launches, etc.
➢ Banking
In the banking sector, computers are used to store details of customers and conduct
transactions, such as withdrawal and deposit of money through ATMs. Banks have
reduced manual errors and expenses to a great extent through extensive use of
computers.
➢ Business
Nowadays, computers are totally integrated into business. The main objective of
business is transaction processing, which involves transactions with suppliers,
employees or customers. Computers can make these transactions easy and accurate.

Prof. GEETHA R Page 12


22POP13/23
People can analyze investments, sales, expenses, markets and other aspects of business
using computers.
➢ Training
Many organizations use computer-based training to train their employees, to save
money and improve performance. Video conferencing through computers allows saving
of time and travelling costs by being able to connect people in various locations.

➢ Arts
Computers are extensively used in dance, photography, arts and culture. The fluid
movement of dance can be shown live via animation. Photos can be digitized using
computers.
➢ Science and Engineering
Computers with high performance are used to stimulate dynamic process in Science
and Engineering. Supercomputers have numerous applications in area of Research and
Development (R&D). Topographic images can be created through computers. Scientists
use computers to plot and analyze data to have a better understanding of earthquake.

1.8 Basic Organization of a computer


The basic organization of a computer system is the processing unit, memory unit, and input-
output devices.

Figure 1: Functional Components of Computer


Prof. GEETHA R Page 13
22POP13/23

Central processing unit: CPU is a brain of computer. It controls the computer system. It
converts data to information. Arithmetic and logic unit: This is a part of CPU. It consists of two
units. One is arithmetic unit and another one is logic unit.

Memory: Computer memory is the storage space in the computer, where data is to be processed and
instructions required for processing are stored
Input unit and output unit: This unit controls input and output devices. Input devices are
keyboard, mouse etc and output devices are printer, monitor, plotter, etc.

CPU (CENTRAL PROCESSING UNIT)


• CPU is considered as the brain of the computer.

• CPU performs all types of data processing operations.


• It stores data, intermediate results, and instructions (program).

• It controls the operation of all parts of the computer

The CPU comprises of following components:


➢ ALU (Arithmetic and Logic Unit)
➢ CU (Control Unit)
➢ Special-purpose registers
➢ A clock

• The ALU is a “super calculator” carrying out all arithmetic tasks and Boolean
operations.
• The CU controls the way data is moved between the various components of computer.
• Both ALU and CU use the service of clock for synchronizing their Operations.
• The CPU uses a few high-speed registers to store the current instruction and its data.
One of the registers, program counter, stores the address of next instruction to be
executed.
• All program instructions are executed using the fetch-decode-execute mechanism.
• The CPUs are rated in GHz (gigahertz).
• Input Unit: It is used to give the input that is data to the computer. It is done with the
help of input devices.
• Ex: Mouse, Keyboard

Prof. GEETHA R Page 14


22POP13/23
• Output Unit: It is used to receive the output (information) from the computer. It is
done with the help ofoutput devices. Ex: Printer, Speaker.

• Memory: Collection of chips on motherboard, where all computer processing and


program instructions arestored. There are two types: Primary Memory and Secondary
Memory.

MEMORY
Memory is an essential resource used by the computer and its users. The CPU needs memory
for the currently running program. Users need memory to backup programs and data that are
not needed.
Computer Memory categorized in to 2 types
1. Primary Memory
2. Secondary Memory

1. Primary memory is the main memory, which stores data and programs, which are currently
needed by CPU.The size is less than the secondary memory and it is costly.
The primary memory which includes the following types:

➢ Random Access Memory (RAM-SRAM and DRAM)


➢ Read Only Memory (ROM-PROM,EPROM, EEPROM)
➢ Cache Memory (L1,L2 and L3)
➢ CPU Registers
RAM (Random Access Memory): It is the main memory, where the user can write
information into RAM and read information from it. It is accessible to users. The RAM is
randomly accessible by user.It is a volatile memory, which means the data, or information is
retained as long as power supply is ON. There are two types of RAM: SRAM and DRAM.

SRAM (Static) DRAM (Dynamic)


Stores information as long as power supply is Loses data in a very short time.
on, reloads every 2ms.
Multiple transistors are used to store 1 bit. One transistor is used to store 1 bit.
It is expensive, faster, and bigger. It is inexpensive, slower, and smaller.
It requires more power. It requires less power.
It is not required to be refreshed. It requires refresh.

Prof. GEETHA R Page 15


22POP13/23

ROM (Read Only Memory): It is a permanent memory that can be read but not written. It is
a nonvolatile memory, which means the data or information is retained even power supply is
not there.It contains a startup program BIOS (Basic Input Output System) which transfers
control to OS.

PROM (Programmable Read Only Memory): It is programmed as per requirement of


customer’s choice. The programmer burns the data into PROM. The data once written cannot
be changed.

EPROM (Erasable Programmable Read Only Memory): It can be rewritten (but only once)
even though it has been previously burned. It is erased by exposing it to UV-rays.

EEPROM (Electrically Erasable Programmable Read Only Memory): It can be erased and
rewritten multiple times. The electric voltage is used to erase the data. The pen drive we use
today is of EEPROM.

Cache Memory: It holds those portions of program that are frequently used by CPU. It acts as
a buffer between CPU and RAM. The CPU first looks for the instructions in cache. It
executes faster than RAM, expensive and limited in size. It has multiple levels:
➢ L1 (Level 1) – smallest and fastest – 32 KB
➢ L2 (Level 2) – present closer to CPU – 256 KB
➢ L3 (Level 3) – shared by cores – 8 MB

Registers: The small number of ultra-fast registers integrated into the CPU represent the
fastest memory of the computer. The CPU does all its work here. Each register has the length
of the computer. The data is loaded into register before processing. Registers are numbered and
a program instruction specifies these numbers. Ex: OR1R2R3 which means multiplication
operation is performed on R1 and R2 is performed and stored in R3.

2. SECONDARY MEMORY
Secondary memory is not directly connected to CPU. It exists inside the machine and also
externally. It is a non-volatile, offline and long-term storage memory. It is slower, cheaper than
primary memory but the capacity is higher.

Prof. GEETHA R Page 16


22POP13/23

Hard disk/ Hard drive/ Fixed disk: It is the oldest secondary storage device. It has more
capacity but, the cost is less comparatively. It is commonly present in laptop with 500GB and
desktop with 1TB. It contains a spindle, which holds one or more platters made up of non-
magnetic material. It has two surfaces which is coated with magnetic material. Each surface
has serially numbered tracks and further broken into sectors or blocks. The disk runs with the
speed of 5400 and 7200 rpm.

Magnetic tape: The magnetic tape is made up of plastic film with one side coated with
magnetic material. It supports 1 TB or more, but 200 TB are also expected. The device is not
fully portable though because, a separate tape drive is required. The data is accessed
sequentially. This makes it unsuitable for backup.

Optical Disks (CD-ROM, DVD ROM, Blu-ray Disk): It is non-volatile read-only memory.
The CD- ROM and DVD-ROM, can hold large volumes of data (700MB to 8.5 GB). The Blu-
ray disk has the capacity upto 50 GB. A laser beam in their drives controls the read and write
operations. A laser beamis used to construct pits and lands by burning selected areas along its
tracks.CD-R, DVD-R: Data can be recorded only once.CD-RW, DVD-RW: Data can be
recorded multiple times.

Flash Memory: It doesn’t have any moving parts, is based on the EEPROM. It is available in
various forms- pen drive, magnetic card (SD Card), solid state disk (SSD). They are portable,
need little power and quite reliable.
The memory stick or pen drive is the most common type of flash memory used on the
computer. It is a small, removable piece of circuit and it connects to the USB port of computer.
The solid state disk is a bigger device meant to replace the traditional magnetic hard disk. The
magnetic card is used mainly in cameras and the most popular is the micro-SD card.
Floppy Diskette: This is represented by a rectangular plastic case containing a thin magnetic
disk. It was available in two sizes (5.25” and 3.5”), offering capacities of 1.2 MB and 1. MB.
It is unsuitable for backup purpose.

Prof. GEETHA R Page 17


22POP13/23

Difference between Primary memory and Secondary memory

Primary Memory Secondary Memory


The size of the primary memory is small. The size of the secondary memory is larger.
Stores the programs and data currently needed It is used to store large amount of data
by the CPU. and programs
Expensive. Inexpensive.
Volatile in nature. Non-volatile in nature.
Ex: RAM, ROM Ex: Hard disk, Optical disk

INPUT DEVICES
Input devices are needed to interact with the OS to perform tasks. Ex: Keyboard, Mouse,
Joystick, Stylus, Scanner etc.

1. Keyboard: Every computer supports a keyboard – either a physical or touchscreen. For


entering data into a computer, the keyboard is the most commonly used input device. It
contains various keys for entering letters, numbers, characters. Although there are some
additional keys for completing various activities, the keyboard layout is identical to that of
a standard typewriter. It is generally available in two different sizes: 84 keys or101/102
keys and for Windows and the Internet, it is also available with 104 keys or 108 keys. It
is connected to a computer system with the help of a USB or a Bluetooth device. The
keyboard has QWERTY layout and contains large number of symbols. Each letter,
numeral or symbol is known as a character, which represents smallest piece of information.
Each character has a unique values called the ASCII (American Standard Code for
Information Interchange) value.

Prof. GEETHA R Page 18


22POP13/23
The keys on the keyboard are:
• Typing Keys: These include the letters of the alphabet. The layout of the
keyboard is known as QWERTY for its first six letters.

• Numeric Keys: These keys are used to enter numeric data and move the cursor.
It is typically made up of 17 keys. When the Num Lock key is set to ON the user
can type numbers, dot or input the symbols /,*,-,+
• Keyboard Shortcuts: These keys include the letter keys (A-Z) and the number
keys (09).
• Control Keys: The pointer and the screen are controlled by these keys. It comes
with four directional arrow keys. Control keys include Home, End, Insert,
Alternate(Alt), Delete, Control(Ctrl), and Escape.

• Special Keys: Enter, Shift, Caps Lock, NumLk, Tab, and Print Screen are some
of the special function keys on the keyboard.
• Function Keys: The 12 keys from F1 to F12 are on the topmost row of
thekeyboard. These are used by the applications and operating systems to input
specific commands.


2. Pointing Devices: GUI (Graphical User Interfaces) like windows need a pointing device
to control the movement of cursor on the screen. This is implemented as mouse in desktop
and touchpad in laptop. The earliest form has a rotating ball and two buttons. The left button
is used for selecting (by clicking once) and execute (by clicking twice). The right button is
used to check and change attributes. The optical mouse uses infrared laser/LED, the wireless
mouse uses radio frequency technology.
Mouse: The mouse is the most used pointing device. While clicking and dragging, the
mouse moves a little cursor across the screen. If you let off of the mouse, the cursor will
Prof. GEETHA R Page 19
22POP13/23
come to a halt. You must move the mouse for the computer to move; it will not move on
its own. As a result, it’s a device that accepts input. Or we can say that a mouse is an input
device that allows you to control the coordinates and movement of the on-screen
cursor/pointer by moving the mouse on a flat surface. The left mouse button can be used
to pick or move items, while the right mouse button displays additional menus when
clicked. It was invented in 1963 by Douglas C. Engelbart.

Types of mouse: Generally, the mouse is of four types:


• Trackball Mouse: Used to control the position of the cursor on the screen. It is
usually used in notebook computers, where it is placed on the keyboard.
• Mechanical Mouse: This type of mouse has a rubber or metal ball at its bottom and
an electronic circuit containing sensors.
• Optical Mouse: It contains a ball inside. The movement of the mouse is detected
using laser technology by using sensors.
• Wireless Mouse / cordless mouse: The movement of the mouse is detected using
radio waves or infrared light waves.

3.Handheld Devices: It is a pocket-sized computing device with a display screen and touch input
and/or miniature keyboard.

Joystick

Joystick is also a pointing device, which is used to move the cursor position on a monitor
screen. It is a stick having a spherical ball at its both lower and upper ends. The lower
spherical ball moves in a socket. The joystick can be moved in all four directions. The
function of the joystick is similar to that of a mouse. It is mainly used in Computer Aided
Designing (CAD) and playing computer games.

Prof. GEETHA R Page 20


22POP13/23

Light Pen

Light pen is a pointing device similar to a pen. It is used to select a displayed menu item or
draw pictures on the monitor screen. It consists of a photocell and an optical system placed
in a small tube.

Track Ball

Track ball is an input device that is mostly used in notebook or laptop computer, instead of
a mouse. This is a ball which is half inserted and by moving fingers on the ball, the pointer
can be moved.

4. Scanner:
A scanner is a type of input device that works in the same way as a photocopier. It’s
used when there’s data on paper that needs to be transferred to the computer’s hard disc
for further processing. The scanner collects images from the source and translates them to
a digital version that can be saved on the hard disks. These graphics can be changed before
they are printed. A scanner is a device that creates a digital image of a document by optically
scanning it. The flatbed scanner doesn’t exceed more than A4 size. It is operated with by
using special software. The document to be scanned is placed on a glass plate covered by
lid.

Types of Scanner: Generally, the scanner is of five types:


• Flatbed Scanner
• Handheld Scanner

Prof. GEETHA R Page 21


22POP13/23
• Sheetfed Scanner
• Drum Scanner
• Photo Scanner

OCR (Optical Character Recognition) is a process of converting printed materials into


text or word processing files that can be easily edited and stored.The steps involved
1. Scanning the text character by character
2. Analyzing the scanned image to translate the character images into character codes.

OMR(Optical Mark Recognition): It is the process of electronically extracting data


from marked fields, such as checkboxes and fill-in fields on printed forms. OMR device
is fed with an OMR sheets that has pen or pencil marks in pre-defined position. It is
scanned by the reader to detect the mark by measuring the reflected light levels.

Magnetic Ink Card Reader (MICR):MICR input device is generally used to verify the
legitimacy of paper documents especially in banks as there are large number of cheques
to be processed every day. The bank's code number and cheque number are printed on the
cheques with a special type of ink that contains particles of magnetic material that are
machine readable.

Prof. GEETHA R Page 22


22POP13/23

5. Audio-visual Input Devices Examples of audiovisual input devices include


microphones, digital cameras, and digital video cameras. Microphones permit audio
input, whether spoken words or ambient sound

Microphone: Microphone is an input device to input sound that is then stored in a digital
form.

OUTPUT DEVICES
The information produced can be heard or seen with the help of output devices. Some of the
output devices are monitor, speaker, printer, plotter etc.

1. Monitor: The monitor is an integral part of computer which displays both text and graphics.
The performance is measured in terms of image quality, resolution, energy consumption.
➢ CRT (Cathode Ray Tube) Monitors: The CRT monitors have a rarefied tube
containing three electron guns. The guns emit electrons create images. They usually
Prof. GEETHA R Page 23
22POP13/23
have resolution of 640*840 pixels. They are large, heavy, energy efficient and produces
lot of heat.


➢ LCD (Liquid Crystal Display) Monitors: The image is formed by applying voltage
on crystals. The backlight is provided by fluorescent light. They consume less power,
generate less heat and have increased life span.

➢ Plasma Monitors : They are thin and flat monitors widely used in television and computers. The
plasma display contains two glass plates that have thousands of tiny cells filled with xenon and
neon gases.
2. Impact Printers: It produces the hardcopy of output. The impact printers are old, noisy.
But, still dot-matrix printer is in usage.
➢ Dot-Matrix Printer: The print head of the dot-matrix printer has either 9 or 24 pins.
When the pins fire against the ribbon, an impression is created on the paper. The speed
is 300 cps and doesn’t produce high quality output. It can produce multiple copies.
➢ Daisy-wheel Printer: It employs a wheel with separate characters distributed along its
outer edge. The wheels can be changed to obtain different set of fonts.
➢ Line Printer: For heavy printing, the line printer is used. It uses a print chain containing
the characters. Hammers strike the paper to print and it rotates at the speed of 1200

Prof. GEETHA R Page 24


22POP13/23
lpm. It is also noisy and is of low-quality.

3. Non-Impact Printers: They are fast, quiet and of high resolution. The most commonly used
non- impact printers are laser and ink-jet printers. The thermal printer is not discussed here
because it uses heat to print on high-sensitive paper.
➢ Laser Printer: It works like a photocopier and uses toner i.e. black magnetic powder.
The image is created in the form of dots and passed from drums on to the paper. It has
built-in RAM which acts as buffer and RAM to store fonts. The resolution varies from
300 dpi to 1200 dpi and the speed is about 20 ppm.
➢ Ink-jet Printer: These are affordable printers. It sprays tiny drops of ink at high
pressure as it moves along the paper. The separate cartridges are available for different
colors. The resolution is about 300 dpi, can print1 to 6 pages/min.
4. Plotters: The plotter can make drawings. It uses one or more automated pens. The
commands are taken from special file called vector graphic files. Depending on type of plotter
either paper or pen moves. It can handle large paper sizes and it is used for creative drawings
like buildings and machines. They are slow and expensive.
5. Projectors: It takes an image from a video source and projects it onto a screen or another
surface.

6. Speakers: with speakers the user can enjoy the music, movie, or a game and the voice will
be spread through the entire room.

Prof. GEETHA R Page 25


22POP13/23

Design and implementation of efficient programs

Prof. GEETHA R Page 26


22POP13/23

Prof. GEETHA R Page 27


22POP13/23

Introduction to C
• C is a general purpose, procedural, structured computer programming language
developed by DennisRitchie in the year 1972 at AT&T Bell Labs.
• C language was developed on UNIX and was invented to write UNIX system software.
• C is a successor of B language.
• There are different C standards: K&R C std, ANSI C, ISO C.

Characteristics of C Programming Language: :

1. Procedural Language
2. Fast and Efficient
3. Modularity
4. Statically Type
5. General-Purpose Language
6. Rich set of built-in Operators
7. Libraries with rich Functions
8. Middle-Level Language
9. Portability
10. Easy to Extend

➢ Procedural Language: In a procedural language like C step by step predefined


instructions are carried out. C program may contain more than one function to perform
a particular task.

➢ Fast and Efficient: C programming language as the been middle-level language


provides programmers access to direct manipulation with the computer hardware but
higher-level languages do not allow this. That’s one of the reasons C language is
considered the first choice to start learning programming languages. It’s fast because
statically typed languages are faster than dynamically typed languages.
➢ Modularity: The concept of storing C programming language code in the form of
libraries for further future uses is known as modularity.

➢ Statically Type: C programming language is a statically typed language. Meaning


the type of variable is checked at the time of compilation but not at run time.

Prof. GEETHA R Page 28


22POP13/23

➢ General Purpose Language: From system programming to photo editing software,


the C programming language is used in various applications. Some of the common
applications where it’s used are as follows:
o Operating systems: Windows, Linux, iOS, Android, OXS
o Databases: PostgreSQL, Oracle, MySQL, MS SQL Server etc.
➢ Rich set of built-in Operators: It is a diversified language with a rich set of built-
in operators which are used in writing complex or simplified C programs.
➢ Libraries with rich Functions: Robust libraries and functions in C help even a
beginner coder to code with ease.
➢ Middle-Level Language: As it is a middle-level language so it has the combined
form of both capabilities of assembly language and features of the high-level
language.
➢ Portability: C language is lavishly portable as programs that are written in C
language can run and compile on any system with either none or small changes.
➢ Easy to Extend: Programs written in C language can be extended means when a
program is already written in it then some more features and operations can be added
to it.
Examples of C :Databases ,Operating system, Language compilers, Assemblers,

Text editors,.

There are three tools to Program development, the solution involves a multi step process
which requires steps like understanding theproblem, developing a solution, writing the program
and testing it.
1. Pseudo code
2. Flowchart
3. Algorithm

1. Pseudo code:
➢ It is an outline of the program that is expressed in a formally styled natural
language. It expresses the design in detail.It is used in planning of computer program
development, for sketching out the structure of the programbefore the actual coding
takes place.

Prof. GEETHA R Page 29


22POP13/23

➢ It is a restatement of the problem as a list of steps in English like format,


describing what must be done to solve the problem.
➢ It is not a programming language but informal way of describing a program andit does
not require strict syntax.
➢ It consists of statements which are a combination of English and C.
➢ Using the pseudo code, a programmer then writes the actual program.

Advantages:
1. It can be written easily
2. It can be read and understood easily
3. Modification is easy
Disadvantages:
1. There is no standard form.
2. One Pseudocode may vary from other for same problem statement.

Examples:

Pseudocode: Addition of two numbers Pseudocode: Area of rectangle

Begin Begin
Read two numbers a, b Read the values of length, breadth
Calculate sum = a+b Calculate area = l x b
Display sum Display area
End End

2. Algorithm
A logical and concise list of steps required to solve a problem is called algorithm.
The representation of the various steps involved in solving problem is called algorithm.
Points for developing an algorithm
➢ Name of the algorithm
➢ Step number
➢ Explanatory statement following the step number
➢ Termination
Example:
Algorithm: To find sum of 2 number
Step 1:Start
Step 2: [input the values of a and b]Read a, b
Step 3:[ find the sum]sum=a+b

Prof. GEETHA R Page 30


22POP13/23

Step 4:[output the result]print sum


Step 5:[finished]Stop

Flowchart
➢ A flowchart is a pictorial representation of an algorithm.
Benefits of using flowcharts are
➢ Being a pictorial representation they are easier to understand.
➢ We can review our logic and debug the program with the help of flowcharts.
➢ Easy to explain a program or discuss the solution.
➢ It separates the logic development and program syntax.

Prof. GEETHA R Page 31


22POP13/23

Example

STRUCTURE OF ‘C’ PROGRAM

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


Documentation Section: It consists of a set of comment line giving the name of the program,
theauthor and other details. Compiler ignores these comments. There are two formats:
1.Line comments //Single line comment
2.Block comments /*Multi line comment*/
Link Section: It provides instruction to the compiler to link functions from system library.

Prof. GEETHA R Page 32


22POP13/23

Definition Section: It defines all symbolic constants.


Global Declaration Section: The variables which are used in more than one function are
called globalvariables and are declared in this section.
main( ) Section: Every ‘C’ program has one main( ) function and it contains two parts:
1. Declaration Part: Here, all the variables used are declared.
2. Executable Part: Here, it contains at least one executable statement.

PREPROCESSOR DIRECTIVES
➢ Every C program is made of one or more preprocessor commands.
➢ This command is present in the beginning of the program
➢ All the preprocessor commands starts with a pound sign[#].
➢ The preprocessor directives are the special instructions that tells the compilerabout
what libraries have to be included in the program.
Ex: #include<stdio.h>
The above command tells the compiler to include the standard input/output library file to the
program.
Where, # is pound sign
include is a keyword used to include library files stdio is standard input/output library
.h is header file
Some of the preprocessor directive given below
#include<conio.h> this is to include console input/output libraryfunctions.
#include<math.h> this is to include mathematical library functions.
#include<string.h> this is to include string library functions.

➢ The executable part of the program begins with the main() function.
• Ex: void main()
void : says that the function doesn’t return any value to the operatingsystem
main: is the function name.
• Note: there should be no semicolon after the function header.
• All the functions in the program are divided into 2 parts:
➢ Declaration section: it describe the data that we are using in thefunction. It is also
called as local declaration.

Prof. GEETHA R Page 33


22POP13/23

➢ Statement section: it contains the instruction to perform specifictask such as reading


input, printing output etc.
The function main starts with an open brace ‘{‘ and terminates with a closebrace ‘}’.

GLOBAL DECLARATIONS
➢ It includes the variables that are used in more than one function.
➢ The variable declared here are visible to all parts of the program
➢ The global variables are declared after preprocessor directives and before main.

COMMENTS
➢ They help the readers to place some program documentations
➢ The compiler ignores the comments when it translates the program toexecutable code.
There are two different formats of comment
1. Block comment
A block comment is used when the comment has several lines .
Sntax: /*-

*/
Everything between the token is ignored by compiler.
2. Line comments
The line comment is used when the comment has only oneline i.e for short comments.
It uses two slashes(//). This format does not require an end-of-comment token.

EXAMPLE:
WRITE A C PROGRAM TO ADD TWO NUMBER
#include<stdio.h>
void main()
{
int a=5,b=6,sum;
sum=a+b;
printf(“sum=%d\n”,sum);
}
or

Prof. GEETHA R Page 34


22POP13/23

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

Files used in a C program


A C program uses four types of files as follows:

1. Source Code File


• This file includes the source code of the program.
• The extension for these kind of files are '.c'. It defines the main and many more
functions written in C.
• main() is the starting point of the program. It may also contain other source code files.
2. Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions
that are shared between various source files.
Advantages of header files:
1. At times the programmer may want to use the same subroutines for different programs. To
do this, he would just compile the code of the subroutine once and link to the resulting object
file in any file in which the functionalities of this subroutine are required.

Prof. GEETHA R Page 35


22POP13/23

2. At times the programmer may want to change or add the subroutines and reflect those
changes in all the programs. For doing this, he will have to only change the source file for the
subroutines, recompile the source code and then recompile and re-link the program.
This tells us that including a header file will make it easier at all levels of the program. If we
need to modify anything then changes are made only in the subroutines after which all the
changes will be reflected.

Common standard header files are:


i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.
The header files are added at the start of the source code so that they can be used by more
than one function of the same file.

3. Object files
• They are the files that are generated by the compiler as the source code file is processed.
• These files generally contain the binary code of the function definitions.
• The object file is used by the linker for producing an executable file for combining the
object files together. It has a '.o' extension.

4. Executable file
• This file is generated by the linker.
• Various object files are linked by the linker for producing a binary file which will be
executed directly.
• They have an '.exe' extension.

Prof. GEETHA R Page 36


22POP13/23

Compiling and Executing a C Program

THE BASIC ‘C’ CHARACTERS

A C character set defines the valid characters that can be used in a source program. The basic
C characterset are:
1. Letters: Uppercase: A,B,C,….,ZLowercase: a,b,c,…..,z
2. Digits: 0,1,2,…..,9
3. Special characters: ! , . # $ ( ) } { etc
4.White spaces: Blank space, Horizontal tab space (\t), carriage return, new line character
(\n), form feedcharacter.

Prof. GEETHA R Page 37


22POP13/23

C – TOKENS
• It is also called as lexical unit.
• The smallest individual unit in ‘C’ program is called as C-Token.
• These are the building blocks of ‘C’ program.
There are 6 types of ‘C’ tokens:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators
6. Special symbols

1. Keywords
➢ Keywords are also called as reserved words.
➢ They already have pre-defined meaning.
➢ Keywords should always be written in lowercase.
➢ The keywords meaning can’t be changed.
➢ Keywords cannot be used as identifiers.
➢ There are 32 keywords in ‘C’ program.

auto double int struct break do


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

2. Identifiers
➢ It refers to the name of the objects.
➢ These are the names given to variables, functions, macros etc.

Prof. GEETHA R Page 38


22POP13/23

The rules to write an identifier are as follows:


1. It must contain only alphabets (A to Z, a to z), numbers (0 to 9) and underscore ( _ ).
2. It must start with alphabet or underscore but not numeric character.
3. It should not contain any special symbols apart from underscore.
4. It should not have any space.
5. Keywords cannot be used as identifiers.
6. Identifiers are case sensitive.
7. Maximum length of an identifier is 31 characters.
Examples:
Valid Identifiers: integer, minimum, sum_ total, row1, _cpps
Invalid Identifiers:float → It is a keyword.
I am → It has space
123_Abc → It is starting with number
N1 + n2 →It contains special symbol (+)

3. Constants
Constants are the values that doesn’t changes during the execution of a program.

Integer Constant

Numeric

Real Constant

Character

String Constant

Figure 3: Types of Constants

Prof. GEETHA R Page 39


22POP13/23

Numerical Constant
Integer Constant: These are the numbers without decimal part.
1. Decimal: It is an integer constant consisting of numbers from 0-9. It can be preceded
by + or –
2. Octal: It is an integer constant consisting of numbers from 0-7. It is preceded by o
3. Hexadecimal: It is an integer constant consisting of numbers from 0-9, A-F (A=10,
B=11, C=12,D=13, E=14, F=15). It is preceded by 0x

Boolean constants
➢ A Boolean data type can take only two values: true[1] and false[0].
➢ If we want to use Boolean datatype in the program then we mustinclude the Boolean
library stdbool.h
Real Constant:
➢ These are the numbers with decimal part.
➢ These are also called as floating point constant.
➢ The floating values can be identified by the suffix ‘F’ or ‘f’
➢ It can be expressed in exponential form.
Ex: 21.5, 2.15 x 102 → 2.15e2
Complex constants
➢ They are coded as 2 parts: real and imaginary separated by + sign.
➢ Real part: is coded as a real format rules.
➢ Imaginary part: is coded as a real number multiplied withimaginary constant [I].
➢ To use the imaginary constant, we have to include complex.h header file
➢ Both real and imaginary parts should be of same type.

Character Constant
Single Character Constant:
➢ These are the values enclosed within single quotes.
Ex:’a’ , ‘1’ etc
➢ Each character have an integer value called as ASCII (American Standard Code for
InformationInterchange) → A: 65, a: 97
➢ Printable Character: All characters are printable except backslash(\) character or
escapesequence.

Prof. GEETHA R Page 40


22POP13/23

➢ Non-Printable Character: The characters with backslash (\) are non printable. Ex: \n,
\t
➢ When a backslash [\] is used before the character then thatbackslash is known as the
‘escape character’.
➢ The escape character says that what follows is not the normalcharacter but it has some
special meaning.
➢ Even though they look like 2 characters , they represent only one.
➢ The escape characters are normally used in printf statement to format the output.
Ex: ‘n’
\n-newline
\t-horizontal tab
\v-vertical tab
\b-backspace
\0-null
\a-alert
\f-formfeed
\r-carriage return
\”
\’
\?
\\
String Constant:
➢ A group of characters together form string.
➢ Strings are enclosed within double quotes. Ex: “h”, “hello”, “ “this refers as empty
string
➢ They end with NULL character (\0).
➢ Ex: “CPPS

C P P S \0

Prof. GEETHA R Page 41


22POP13/23

CODING CONSTANTS
There are three ways to code/define constants in program
➢ Literal constant
A literal is an unnamed constant used to specify data.
If there is some data that cannot be changed in the program, thenwe can simply code
the data value itself in a statement.
Ex: a=b+5;
➢ Symbolic Constants/ Defined constant
Another way to designate a constant is to use the preprocessorcommand “#define”.
The define commands are usually placed at the beginning of theprogram.
Ex: #define Pi 3.14main()
{
A=b*Pi
}
In program whenever it finds Pi, it is replaced by value3.142
➢ Qualified Constant /Memory constant
It uses C type qualifier “const” to indicate data cannot be changed.
Syntax: const type identifier=value;
Ex: const float cpi=3.14;
It is same as literals, but we are giving a symbolic name to it.
Usually to represent the constant variable we prefix ‘c’ with the variable name.

Example program:
#include<stdio.h>
#define PI 3.1416 // define constant
void main()
{
const float cpi=3.1416; //memory constant
printf(“literal constant:%f\n”,3.1416); //literal constant
printf(“ defined constant:%f\n”,PI);
printf(“memory constant:%f\n”cpi);
}
Output:

Prof. GEETHA R Page 42


22POP13/23

literal constant: 3.1416


defined constant: 3.1416
memory constant: 3.1416

DATA TYPES

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


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

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

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

2. Floating point data type:


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

Prof. GEETHA R Page 43


22POP13/23

Data type Keyword Size


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

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

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

5. Void:
➢ It is a special data type that has no value.
➢ It doesn’t have size.
➢ It is used for returning the result of function that returns nothing.

VARIABLES

✓ A variable is a name given to memory location whose value changes during execution.

Declaration:

Syntax: datatype variable_list;


Where,
datatype Any built in data type
variable_list Identifiers that specifies variable name.
Example: int a;
Where,
int is the built in data type
a is variable of type int.

Prof. GEETHA R Page 44


22POP13/23

Initialization:

Syntax: datatype variable_name = value;


Where,
datatype →Any built in data type
variable_name →Identifier that specifies variable name. value →The data
which will be stored in variable name.

Example: int a = 10;


Where,
int →data type
a →variable name
10→ value

MANAGING INPUT AND OUTPUT OPERATIONS

✓ Reading, processing and writing of data are three essential functions of a computer program.
✓ There are two methods. The first method is to assign the values and the second method is to use input
function scanf to read data and output function printf to write data.
✓ Ex: #include<stdio.h> Includes function calls such as printf() and scanf() into the source code when
compiled.

READING A CHARACTER
✓ The simplest way of all input/output operations is reading a character from the ‘standard input’ unit
(usually keyboard) and writing it to the ‘standard output’ (usually the screen).
✓ Reading a single character can be done by using the function getchar and it does not have any parameter.

Syntax: variable_name = getchar( );

Where, variable_name is valid and has been declared in char type.

Example: char name;


name = getchar( );
✓ The getchar function can also be used to read the characters successively until the return key is pressed.
✓ The character function are contained in the file type ctype.h and therefore the preprocessor directive
#include<ctype.h> is included.
✓ And the functions of ctype.h returns 1 if (TRUE) and 0 if (FALSE).

Function Test
isalnum(c) Is c alphanumeric character?

Prof. GEETHA R Page 45


22POP13/23

isalpha(c) Is c alphabetic character?


isdigit(c) Is c a digit?
islower(c) Is c a lower case letter?
isupper(c) Is c a upper case letter?
isspace(c) Is c a white case character?
ispunct(c) Is c a punctuation mark?
isprint(c) Is c a printable character?

Example Program:

#include<stdio.h>

#include<ctype.h>

void main( )
{
char key;
printf(“Enter any key\n”);
key=getchar( );
if(isalpha(key))
printf(“The entered key is a letter\n”);
else if(isdigit(key))
printf(“The entered key is a digit\n”);
else
printf(“The entered key is not alphanumeric\n”);
}

OUTPUT:
Enter any key Enter any key Enter any key
A 7 $
The entered key is a letter The entered key is a digit The entered key is not alphanumeric

WRITING A CHARACTER
✓ Writing a single character can be done by using the function putchar.

Prof. GEETHA R Page 46


22POP13/23

Syntax: putchar(variable_name);

Where, variable_name is valid and has been declared in char type.

Example: name=’y’;
putchar(name);

Will display the character y on the screen


✓ The characters entered can be converted into reverse i.e., from upper to lower case and vice versa.
✓ The functions used to convert are toupper, tolower.

Example Program:
#include<stdio.h>
#include<ctype.h>
void main( )
{
char alphabet;
printf(“Enter any alphabet\n”);
alphabet=getchar( );
if(islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
}
OUTPUT:

Enter any alphabet Enter any alphabet


A a

Prof. GEETHA R Page 47


22POP13/23

FORMATTED INPUT
✓ Formatted input refers to an input data that has been arranged in particular format.
✓ Ex: 152 Rajesh
✓ In the above example the first part contains integer and the second part contains
characters. This ispossible with the help of scanf function.
Syntax: scanf(“control string”, arg1, arg2,…..,argn);

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

✓ The input field may be skipped using * in the place of field width.

✓ The scanf function can read single character or more than one character using %c or %s.

Rules for scanf:


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

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

Prof. GEETHA R Page 48


22POP13/23

Code Meaning
%c Read a single character
%d Read a decimal integer
%e, %f, %g Read a floating point value
%h Read a short integer
%i Read a decimal integer
%o Read a octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a hexadecimal integer
%[ ] Read a string of word

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

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

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

✓ Control string contains three types of items:


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

✓ The printf can contain flags (0 + - )


0 → fill in extra positions with 0’s instead of spaces

a=7777
printf(“a = %07d”, a);
%07d
0 0 0 7 7 7 7

Width of 7 memory space is allocated and


padded with leading zeroes

- → Left justify text instead of right justify text

a= 7777;

Prof. GEETHA R Page 49


22POP13/23

printf(“a = % -7d”, a);


% -7d
Width of 7 memory space is allocated and
7 7 7 7 printed from left side (left justify)

+→Print sign of number (whether positive or negative)


➢ Example with format specifier %d:
a=10, b=77;
printf(“%d %d”, a , b);

Output:
10 77

➢ Example with format specifier %f:


x=10.776;
printf(“%6.3f %”, x );

%6.3f 6.3f means totally 6 locations are allocated out of


1 0 . 7 7 6 which 3 is for number of decimal places.

➢ Example with \n and \t:


a=10, b=77, c=88;
printf(“a=%d\n b=%d\tc=%d”, a , b, c);

Output:
a=10
b=77
c=88
➢ Example with size value:
a=10, b=7777, c=88;
printf(“a=%4d\n b=%7d”, a , b);
%4d
Width of 4 memory space is allocated and
printed from right side

Prof. GEETHA R Page 50


22POP13/23

%7d
7 7 7 7

Width of 7 memory space is allocated and


printed from right side (right justify)

❖ The below table shows the scanf format codes commonly used.
Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floating point value in exponent form
%f Print a floating point value without exponent
%g Print a floating point value with or without exponent
%h Print a short integer
%i Print a decimal integer
%o Print a octal integer
%s Print a string
%u Print an unsigned decimal integer
%x Print a hexadecimal integer
%[ ] Print a string of word
The l can be used as a prefix for long integer. Ex: %ld
➢ General syntax of field-width/size for different data types:

• %wd → Example: %6d


• %w.pf → Example %6.2f
• %w.ps →Example %10.4s
– w means total field size/width
– P means precision (tells how many decimal places to be printed in case of float)
and
– How many characters to be printed in case of strings

Examples: 9 8 7 6

a=9876;
9 8 7 6
printf(“%d”, a);
printf(“%6d”,a); 9 8 7 6

printf(“%-6d”,a); 9 8 7 6

printf(“%3d”,a);

NOTE: String input/output function: gets() and puts( )


➢ gets and puts are line oriented input output functions available in the <stdio.h> header file.
➢ gets():Alternative method to read strings is gets() (read it as get string) function which is

Prof. GEETHA R Page 51


22POP13/23

anunformatted string input function. Advantage of gets()is it can read multi-word strings.
➢ Example: charname[10];
gets(name);

Say input is:


N E W Y O R K

The complete string “NEW YORK” is read by gets( ).

➢ puts():This function can be used to display entire string on monitor screen without the help of
%s specifier.
➢ Example: char name[ ] = “Bengaluru”
puts(name);
puts( ) will display the string value stored in parameter passed to it on monitor. In this case it is—
Bengaluru.

Prof. GEETHA R Page 52

You might also like