module 1 pop c
module 1 pop 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
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.
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.
Computer Generations
The computer of each generation is smaller, faster and more powerful than preceding
generation. There are five computer generations.
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.
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.
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
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
Main Features:
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.
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
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.
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
➢ 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.
➢ 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.
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.
• 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
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:
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.
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.
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.
INPUT DEVICES
Input devices are needed to interact with the OS to perform tasks. Ex: Keyboard, Mouse,
Joystick, Stylus, Scanner etc.
• 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.
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.
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.
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.
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
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.
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.
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
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.
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:
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
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.
Example
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.
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
#include<stdio.h>main()
{
int a,b,sum;
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“sum=%d\n”,sum);
}
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.
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.
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.
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.
2. Identifiers
➢ It refers to the name of the objects.
➢ These are the names given to variables, functions, macros etc.
3. Constants
Constants are the values that doesn’t changes during the execution of a program.
Integer Constant
Numeric
Real Constant
Character
String Constant
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.
➢ 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
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:
DATA TYPES
❖ 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
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:
Initialization:
✓ 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.
Function Test
isalnum(c) Is c alphanumeric 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.
Syntax: putchar(variable_name);
Example: name=’y’;
putchar(name);
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:
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.
❖ The below table shows the scanf format codes commonly used.
Code Meaning
%c Read a single character
%d Read a decimal integer
%e, %f, %g Read a floating point value
%h Read a short integer
%i Read a decimal integer
%o Read a octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a hexadecimal integer
%[ ] Read a string of word
FORMATTED OUTPUT
✓ The printf function is used for printing the captions and results.
a=7777
printf(“a = %07d”, a);
%07d
0 0 0 7 7 7 7
a= 7777;
Output:
10 77
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
%7d
7 7 7 7
❖ 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:
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);
anunformatted string input function. Advantage of gets()is it can read multi-word strings.
➢ Example: charname[10];
gets(name);
➢ 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.