0% found this document useful (0 votes)
26 views64 pages

Mod 1

Uploaded by

Arjun Arjun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views64 pages

Mod 1

Uploaded by

Arjun Arjun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Module 1

Syllabus: Introduction to computers, input and output devices, designing efficient programs. Introduction
to C, Structure of C program, Files used in a C program, Compilers, Compiling and executing C
programs, variables, constants, Input/output statements in C.

1.1 Computer
 A computer 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.

m
1.2 Characteristics of Computers

co
e.
Figure 1.1. Characteristics of computers
dg
1. Speed
 Computers can perform millions of operations per second.
 The speed of computers is usually given in nanoseconds and picoseconds, where 1 nanosecond
= 1 × 10 −9 seconds and 1 picosecond = 1 × 10 −12 seconds.

2. Accuracy
ue

 A computer is a very fast, reliable, and robust electronic device.


 It always gives accurate results, provided the correct data and set of instructions are input to it.
 This clearly means that the output generated by a computer depends on the given instructions
and input data.
 If the input data is wrong, then the output will also be erroneous. In computer terminology, this
is known as garbage-in, garbage-out (GIGO).
vt

3. Automation
 Besides being very fast and accurate, computers are automatable devices that can perform a task
without any user intervention.
 The user just needs to assign the task to the computer, after which it automatically controls
different devices attached to it and executes the program instructions.

4. Diligence
 Computers never get tired of a repetitive task. It can continually work for hours without creating
errors.
 Even if a large number of executions need to be executed, each and every execution requires the
same duration, and is executed with the same accuracy.
5. Versatile
 Versatility is the quality of being flexible. Today, computers are used in our daily life in
different fields.
 For example, they are used as personal computers (PCs) for home use, for business-oriented
tasks, weather forecasting, space exploration, teaching, railways, banking, medicine, and so on,
indicating that computers can perform different tasks simultaneous

Memory
 Computers have internal or primary memory (storage space) as well as external or secondary
memory.
 The computer stores a large amount of data and programs in the secondary storage space.
 The stored data and programs can be retrieved and used whenever required.
 Secondary memory is the key for data storage. Some examples of secondary devices include

m
floppy disks, optical disks (CDs and DVDs), hard disk drives (HDDs), and pen drives.

6. No IQ
 Although the trend today is to make computers intelligent by inducing artificial intelligence

co
(AI) in them, they still do not have any decision-making abilities of their own. They need
guidance to perform various tasks.

7. Economical
 Today, computers are considered as short-term investments for achieving long-term gains.
e.
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.
 For example, using the conventional postal system to send an important document takes at least
dg

two to three days, whereas the same information when sent using the Internet (e-mail) will be
delivered instantaneously.

1.3 Stored Program Concept


 All digital computers are based on the principle of stored program concept.
 The following are the key characteristic features of this concept:
ue

 Before any data is processed, instructions are read into memory.


 Instructions are stored in the computer‟s memory for execution.
 Instructions are stored in binary form (using binary numbers—only 0s and 1s).
 Processing starts with the first instruction in the program, which is copied into a control
unit circuit. The control unit executes the instructions.
vt

 Instructions written by the users are performed sequentially until there is a break in
the current flow.
 Input/Output and processing operations are performed simultaneously. While data is being
read/written, the central processing unit (CPU) executes another program in the memory that
is ready for execution.

1.3.1 Types of Stored Program Computers


1. Shared Memory Architecture
 A computer with a Von Neumann architecture stores data and instructions in the same memory.
 There is a serial machine in which data and instructions are selected one at a time.
 Data and instructions are transferred to and from memory through a shared data bus. Since there
is a single bus to carry data and instructions, process execution becomes slower.

2. Distributed Memory Architecture


 Later Harvard University proposed a stored program concept in which there was a separate
memory to store data and instructions.
 Instructions are selected serially from the instruction memory and executed in the processor.
When an instruction needs data, it is selected from the data memory. Since there are separate
memories, execution becomes faster.

m
co
Figure 1.2. Von Neumann architecture (a) Shared memory for instructions and data (b)
Separate memories for instructions and data

1.4 History of Computers


e.
 Timeline of Developments
300 BC: The abacus was an early aid for mathematical computations and was designed to aid
human‘s memory while performing calculations.
1822: Charles Babbage designed a steam-driven calculating machine that could compute tables
dg

of numbers.
1890: a punched card system was designed for the calculations.
1936: Turing machine were designed, which were capable of computing anything that is
computable.
1941: It was the first time a computer could store information in its main memory.
1943–1944:
ue

 Electronic Numerical Integrator and Calculator (ENIAC) were built.


 It is considered as the grandfather of digital computers.
 It filled a 20 × 40 feet room and had 18,000 vacuum tubes.
1946: UNIVAC was designed, which was the first commercial computer for business and
government applications.
vt

1947: vacuum tubes in computers were replaced by transistors.


1953: Developed the first computer language COBOL.
1954: The FORTRAN programming language was developed.
1958: invented integrated circuit, which is commonly known as the computer chip.
1964: developed a prototype of the modern computer, with a mouse and a graphical user
interface (GUI). This was a remarkable achievement as it shifted computers from a specialized
machine for scientists and mathematicians to general public.
1969: Unix operating system was developed at Bell Labs. It was written in the C programming
language and was designed to be portable across multiple platforms.
1970: DRAM chip was introduced by Intel.
1971: invented the floppy disk which allowed data to be shared among computers.
1973: developed Ethernet for connecting multiple computers and other hardware.
1974–1977: Personal computers started becoming popular.
1975: Paul Allen and Bill Gates started writing software using the new BASIC language. They
both formed their own software company, Microsoft.
1976: Apple Computers and developed Apple I, the first computer with a single-circuit board
1977: Apple II was launched that offered colour graphics and incorporated an audio cassette
drive for storage.
1978: a word processor application, was released by MicroPro International.
1979: the first computerized spreadsheet program for personal computers, was unveiled.
1981: The first IBM personal computer was introduced that used Microsoft‘s MS-DOS
operating system. The term PC was popularized.
1983: The first laptop was introduced.
1985: Microsoft announced Windows as a new operating system.
1986: Compaq introduced Deskpro 386 in the market, which was a 32-bit architecture machine
that provides speed comparable to mainframes.
1990: Invented the World Wide Web with HTML as its publishing language.

m
1993: The Pentium microprocessor introduced the use of graphics and music on PCs.
1994: PC games became popular.
1996: developed the Google search engine at Stanford University.
1999: The term Wi-Fi was introduced when users started connecting to the Internet without
wires.

co
2001: Apple introduced Mac OS X operating system, which had protected memory architecture
and pre-emptive multi-tasking, among other benefits. To stay competitive, Microsoft launched
Windows XP.
2003: The first 64-bit processor, AMD‘s Athlon 64, was brought into the consumer market.
2004: Mozilla released Firefox 1.0 and in the same year Facebook, a social networking site, was
launched.
e.
2005: YouTube, a video sharing service, was launched. In the same year, Google acquired
Android, a Linux-based mobile phone operating system.
2006: Apple introduced MacBook Pro, its first Intelbased, dual-core mobile computer.
2007: Apple released iPhone, which brought many computer functions in the smartphone.
dg

2009: Microsoft launched Windows 7 in which users could pin applications to the taskbar.
2010: Apple launched iPad, which revived the tablet computer segment.
2011: Google introduced Chromebook, a laptop that runs on the Google Chrome operating
system.
2015: Apple released the Apple Watch. In the same year, Microsoft launched Windows 10.
ue

1.4.1 Generations of Computers


1. First Generation (1942–1955)
Hardware Technology
First generation computers were manufactured using thousands of vacuum tubes.
vt

Memory
 Electromagnetic relay was used as primary memory and
 Punched cards were used to store data and instructions.

Software Technology
 Programming was done in machine or assembly language.

Used for Scientific applications

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


Highlights
 They were the fastest calculating device.
 Computers were too bulky and required a complete room for storage
 Highly unreliable as vacuum tubes emitted a large amount of heat and burnt frequently
 Required air-conditioned rooms for installation
 Costly
 Difficult to use
 Required constant maintenance because vacuum tubes used filaments that had limited
life time. Therefore, these computers were prone to frequent hardware failures.

2. Second Generation (1955–1964)


Hardware Technology
 Second generation computers were manufactured using transistors.
 Transistors were reliable, powerful, cheaper, smaller, and cooler than vacuum tubes.

Memory
 Magnetic core memory was used as primary memory;

m
 Magnetic tapes and magnetic disks were used to store data and instructions.
 These computers had faster and larger memory than the first generation computers.

Software Technology

co
 Programming was done in high level programming languages. Batch operating system
was used.

Used for Scientific and commercial applications


e.
Examples Honeywell 400, IBM 7030, CDC 1604, UNIVAC LARC

Highlights
 Faster, smaller, cheaper, reliable, and easier to use
 They consumed 1/10th the power consumed by first generation computers
dg

 Bulky in size
 Dissipated less heat than first generation computers
 Costly
 Difficult to use.
ue

3. Third Generation (1964–1975)


Hardware Technology
 Third generation computers were manufactured using integrated chips (ICs).
 ICs consist of several components such as transistors, capacitors, and resistors on a
single chip to avoid wired interconnections between components.
 These computers used SSI and MSI technology. Minicomputers came into existence.
vt

Memory
 Larger magnetic core memory was used as primary memory; larger capacity magnetic
tapes and magnetic disks were used to store data and instructions.

Used for Scientific, commercial, and interactive online applications.

Highlights
 Faster, smaller, cheaper, reliable, and easier to use than the second generation computers
 They consumed less power than second generation computers.
 Bulky in size and required a complete room for installation
 Dissipated less heat than second generation computers
 Costly
 Easier to use and upgrade

Software Technology
 Programming was done in high level programming languages such as FORTRAN,
COBOL, Pascal, and BASIC.
 Time sharing operating system was used.
 Software was separated from the hardware.

4. Fourth Generation (1975–1989)


Hardware Technology
 Fourth generation computers were manufactured using ICs with LSI (Large Scale
Integrated) and later with VLSI technology (Very Large Scale Integration).
 Microcomputers came into existence.

m
 Use of personal computers became widespread.
 High speed computer networks in the form of LANs, WANs, and MANs started
growing.

co
Memory
 Semiconductor memory was used as primary memory; large capacity magnetic disks
were used as built in secondary memory.
 Magnetic tapes and floppy disks were used as portable storage devices.
e.
Software Technology
 Programming was done in high level programming language such as C and C++.
 Graphical User Interface (GUI) based operating system (e.g. Windows) was
introduced. It had icons and menus among other features to allow computers to be used
dg
as a general purpose machine by all users.
 UNIX was also introduced as an open source operating system. Apple Mac OS and MS
DOS were also released during this period.
 All these operating systems had multi-processing and multiprogramming capabilities.

Used for Scientific, commercial, interactive online, and network applications.


ue

Examples IBM PC, Apple II, TRS-80, VAX 9000, CRAY1, CRAY-2, CRAY-X

Highlights
 Faster, smaller, cheaper, powerful, reliable, and easier to use than the previous
generation computers.
vt

5. Fifth Generation (1989–Present)


Hardware Technology
 Fifth generation computers are manufactured using ICs with ULSI (Ultra Large Scale
Integrated) technology.
 The use of Internet became widespread and very powerful mainframes, desktops,
portable laptops, and smartphones are being used commonly.
 Supercomputers use parallel processing techniques.

Memory
 Semiconductor memory is used as primary memory;
 large capacity magnetic disks are used as built-in secondary memory.
 portable storage devices like optical disks and USB flash drives are used.
Software Technology
 Programming is done in high-level programming languages such as Java, Python, and
C#.
 Graphical User Interface (GUI)-based operating systems such as Windows, Unix, Linux,
Ubuntu, and Apple Mac are being used.
 These operating systems are more powerful and user friendly than the ones available in
the previous generations.

Used for Scientific, commercial, interactive online, multimedia (graphics, audio, video), and
network applications.

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

m
Highlights
 Faster, smaller, cheaper, powerful, reliable, and easier to use than the previous
generation computers.

co
 Speed of microprocessors and the size of memory are growing rapidly.
 High-end features available on the microprocessors
 They consume less power than computers of prior generations.

1.5 Classification of Computers


e.
 Computers can be broadly classified into four categories based on their speed, amount of data
that they can process, and price:
 Supercomputers
 Mainframe computers
dg
 Minicomputers
 Microcomputers
ue
vt

Figure 1.3. Classification of computers


1. Supercomputers
 The supercomputer is the fastest, most powerful, and most expensive computer.
 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.
 A single supercomputer can support thousands of users at the same time.
 Such computers are mainly used for weather forecasting, nuclear energy research, aircraft
design, automotive design, online banking, controlling industrial units, etc.
2. Mainframe Computers
 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.
 Support multiple processors.
 The two types of terminals that can be used with mainframe systems are as follows:
1. 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.
2. Intelligent Terminals:
 Intelligent terminals have their own processor and thus can perform some processing
operations.
 Usually, PCs are used as intelligent terminals to facilitate data access and other services from

m
the mainframe system.
 Mainframe computers are typically used as servers on the World Wide Web.
 They are also used in organizations such as banks, airline companies, and universities, where a
large number of users frequently access the data stored in their databases.

co
3. Minicomputers
 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.
 Minicomputers are widely used in business, education, hospitals, government organizations, etc.
e.
While some minicomputers can be used only by a single user, others are specifically designed to
handle multiple users simultaneously.
 Minicomputers can also be used as servers in a networked environment.
dg

4. Microcomputers
 Microcomputers, commonly known as PCs, are very small and cheap.
 Many computer hardware companies copied this design and termed their microcomputers as
PC-compatible.
 PCs can be classified into the following categories:
Desktop PCs, Laptops, Workstations, Network Computers and Handheld Computers.
ue

(i) Desktop PCs A desktop PC is the most popular model of PCs.


(ii) Laptops: Laptops operate on a battery. The memory and storage capacity of a laptop is
almost equivalent to that of a desktop computer. laptops have the same features and processing
speed as the most powerful PCs.
(iii) Workstations: Workstation computers have advanced processors, more RAM and storage
vt

capacity than PCs.


(iv) Network Computers: Network computers have less processing power, memory, and
storage than a desktop computer. Some network computers do not have any storage space and
merely rely on the network‘s server for data storage and processing tasks
(v) Handheld Computers: Handheld computers are very small in size, and hence they have
small-sized screens and keyboards. Some examples of handheld computers are as follows:
Smartphones, Tablet PCs.
a. 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.
b. 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.
Uses The following are the uses of Tablet PCs:
• View presentations
• Videoconferencing
• Reading e-books, e-newspaper
• Watching movies
• Playing games
• Sharing pictures, video, songs, documents, etc.
• Browsing the Internet
• Keeping in touch with friends and family on popular social networks, sending emails
• Business people use them to perform tasks such as editing a document, exchanging
documents, taking notes, and giving presentations
• Tablets are best used in crowded places such as airports and coffee shops.

m
1.6 Applications of Computers
1. Word processing
 Word processing software enables users to read and write documents.
 Users can also add images, tables, and graphs for illustrating a concept.

co
 The software automatically corrects spelling mistakes and includes copy–paste features.

2. Internet
 The Internet is a network of networks that connects computers all over the world.
 It gives the user access to an enormous amount of information, much more than available in any
library.
e.
 Using e-mail, the user can communicate in seconds with a person who is located thousands of
miles away.
 Chat software enables users to chat with another person in real-time.
 Video conferencing tools are becoming popular.
dg

3. Digital video or audio composition


 Computers make audio or video composition and editing very simple.
 Graphics engineers use computers for developing short or full-length films and creating 3-D
models and special effects in science fiction and action movies.
ue

4. Desktop publishing
 Desktop publishing software enables us to create page layouts for entire books.

5. e-Business
 e-Business or electronic business is the process of conducting business via the Internet.
 This may include buying and selling of goods and services using computers and the Internet.
vt

 Companies today use e-commerce applications for marketing, transaction, processing, and
product and customer services processing.
Business-to-consumer or B2C: In this form of electronic commerce, business companies
deploy their websites on the Internet to sell their products and services to the customers. On
their websites, they provide features such as catalogues, interactive order processing system,
secure electronic payment system, and online customer support.
Business-to-business or B2B: This type of electronic commerce involves business transactions
performed between business partners (customers are not involved). For example, companies use
computers and networks (in the form of extranets) to order raw materials from their suppliers.
Companies can also use extranets to supply their products to their dealers.
Consumer-to-consumer or C2C: This type of electronic commerce enables customers to carry
business transactions among themselves. For example, on auction websites, a customer sells
his/her product which is purchased by another customer.
Electronic banking Electronic banking, also known as cyber banking or online banking,
supports various banking activities conducted from home, a business, or on the road instead of a
physical bank location.

6. Bioinformatics
 Bioinformatics is the application of computer technology to manage large amount of biological
information.
 Computers are used to collect, store, analyse, and integrate biological and genetic information to
facilitate gene-based drug discovery and development.
 Bioinformatics is an interdisciplinary field of molecular biology, computer science, statistics,
and mathematics.

7. Health care

m
 Computers have also become a necessary device in the health care industry. The following are
areas in which computers are extensively used in the health care industry:
Storing records: computers are first and foremost used to store the medical records of patients.
Surgical procedures Computers are used for certain surgical procedures. They enable the
surgeon to use computer to control and move surgical instruments in the patient‘s body for a

co
variety of surgical procedures.
Better diagnosis and treatment Computers help physicians make better diagnoses and
recommend treatments.

8. Geographic Information System and Remote Sensing


e.
 A geographic information system (GIS) is a computer based tool for mapping and analysing
earth.
 It integrates database operations and statistical analysis to be used with maps.
 Remote sensing is a sub-field of geography, which can be applied in the following areas to
dg
collect data of dangerous or inaccessible areas for the following: Monitoring deforestation,
Studying features of glaciers, etc.

9. Meteorology
 Meteorology is the study of the atmosphere. Meteorology has applications in many diverse
fields. Some of the applications include the following:
ue

 Weather forecasting It includes application of science and technology to predict the state of the
atmosphere (temperature, precipitation, etc.) for a future time and a given location.
 Aviation meteorology Aviation meteorology studies the impact of weather on air traffi c
management.
 Agricultural meteorology Agricultural meteorology deals with the study of effects of weather
and climate on plant distribution, crop yield, water-use efficiency, plant and animal
vt

development.
 Nuclear meteorology Nuclear meteorology studies the distribution of radioactive aerosols and
gases in the atmosphere. Maritime meteorology Maritime meteorology is the study of air and
wave forecasts for ships operating at sea.
 Multimedia and Animation Multimedia and animation that combines still images, moving
images, text, and sound in meaningful ways is one of most powerful aspects of computer
technology. We all have seen cartoon movies, which are nothing but an example of computer
animation.

10. Legal System


 Lawyers use computers to look through millions of individual cases and find whether similar or
parallel cases have been approved, denied, criticized, or overruled in the past.
11. Retail Business
 Computers are used in retail shops to enter orders, calculate costs, and print receipts.

12. Sports
 In sports, computers are used to compile statistics, identify weak players and strong players by
analysing statistics, sell tickets, create training programs and diets for athletes, and suggest
game plan strategies based on the competitor‘s past performance.

13. Travel and Tourism


 Computers are used to prepare tickets, monitor the train‘s or airplane‘s route, and guide the
plane to a safe landing.

14. Simulation

m
 Simulation of automobile crashes or airplane emergency landings is done to identify potential
weaknesses in designs without risking human lives.

15. Education
 A computer is a powerful teaching aid and can act as another teacher in the classroom. Teachers

co
use computers to develop instructional material.

16. Industry and Engineering


 Computers are found in all kinds of industries, such as thermal power plants, oil refineries, and
chemical industries, for process control, computer-aided designing (CAD), and computer-aided
e.
manufacturing (CAM).

17. Robotics
 Robots are computer-controlled machines mainly used in the manufacturing process in extreme
dg
conditions where humans cannot work.

18. Decision Support Systems


 Computers help managers to analyse their organization‘s data to understand the present scenario
of their business, view the trends in the market, and predict the future of their products.
ue

19. Expert Systems


 Expert systems are used to automate the decision-making process in a specific area, such as
analysing the credit histories for loan approval and diagnosing a patient‘s condition for
prescribing an appropriate treatment.

1.7 Basic Organization of a Computer


vt

 A computer is an electronic device that performs five major operations:


 Accepting data or instructions (input)
 Storing data
 Processing data
 Displaying results (output)
 Controlling and coordinating all operations inside a computer.

Input: This is the process of entering data and instructions (also known as programs) into the
computer system. The data and instructions can be entered by using different input devices such as
keyboard, mouse, scanner, and trackball.
m
Figure 1.4. Block diagram of a computer

Storage: Storage is the process of saving data and instructions permanently in the computer so that

co
they can be used for processing.
A computer has two types of storage areas:
Primary storage: Primary storage, also known as the main memory, is the storage area that is
directly accessible by the CPU at very high speeds. Primary storage space is very expensive and
therefore limited in capacity.Another drawback of main memory is that it is volatile in nature; that
is, as soon as the computer is switched off, the information stored gets erased. Hence, it cannot be
e.
used as a permanent storage of useful data and programs for future use. Example of primary storage
is random access memory (RAM).
Secondary storage Also known as auxiliary memory. It is cheaper, non-volatile, and used to
permanently store data and programs of those jobs that are not being currently executed by the CPU.
dg

Output: Output is the process of giving the result of data processing to the outside world. The
results are given through output devices such as monitor, and printer. Since the computer accepts
data only in binary form and the result of processing is also in binary form, the result cannot be
directly given to the user. The output devices, therefore, convert the results available in binary codes
into a human-readable language before displaying it to the user.
ue

Control: The control unit (CU) manages and controls all the components of the computer system. It
is the CU that decides the manner in which instructions will be executed and operations performed.
It takes care of the step-by-step processing of all operations that are performed in the computer.
The CPU is a combination of the arithmetic logic unit (ALU) and the CU. The CPU is better
known as the brain of the computer system because the entire processing of data is done in the
vt

ALU, and the CU activates and monitors the operations of other units (such as input, output, and
storage) of the computer system.

Processing: The process of performing operations on the data as per the instructions specified by
the user (program) is called processing. Data and instructions are taken from the primary memory
and transferred to the ALU, which performs all sorts of calculations.

1.8 Motherboard
 The motherboard, also known as the main board or the parent board is the primary component
of a computer. It is used to connect all the components of the computer.
Characteristics of a Motherboard
 A motherboard can be classified depending on the following characteristics:
 Form factor
 Chipset
 Type of processor socket used
 Input–Output connectors

Form factor: Form factor refers to the motherboard‘s geometry, dimensions, arrangement, and
electrical requirements.

Integrated components: Some of the motherboard‘s components are integrated into its printed
circuitry. These include the following:
 The chipset is a circuit that controls the majority of the computer‘s resources such as the bus

m
interface with the processor, cache memory, RAM, and expansion cards.
 CMOS clock and battery
 BIOS
 System bus and expansion bus

co
Chipset: The chipset is an electronic circuit that basically coordinates data transfers between the
different components of the computer.
Some chipsets may include a graphics or audio chip, which makes it unnecessary to install a
separate graphics card or sound card.
e.
CMOS clock and battery: The real-time clock (or RTC) is a circuit that is used to synchronize the
computer‘s signals. When the computer is switched off, the power supply stops providing electricity
to the motherboard. The CMOS chip is powered by a battery located on the motherboard.
dg

Processor socket: The processor (also called the microprocessor) is the brain of the computer. The
processor is characterized by its speed or frequency, which is the rate at which it executes
instructions.

RAM connectors RAM is the primary storage area that stores data while the computer is running.
However, its contents are erased when the computer is turned off or restarted.
ue

Expansion slots: Expansion slots are compartments into which expansion cards can be inserted.
Such cards render new features or enhance the computer‘s performance.

I/O connectors: The motherboard has a number of input– output sockets on its rear panel, some of
vt

which include:
 A serial port to connect some old peripherals
 A parallel port to connect old printers
 USB ports to connect more recent peripherals such as mouse and pen drive.
 RJ45 connector (also known as LAN or Ethernet port) to connect the computer to a network.
It corresponds to a network card integrated into the motherboard.
 Video graphics array (VGA) connector to connect a monitor. This connector interfaces with
the built-in graphics card.
 Audio plugs that include the line in, line out, and microphone to connect sound speakers, hi-
fi system, or microphone. This connector interfaces with the built-in sound card.
m
co
e.
dg

Figure 1.5. Computer‟s motherboard


ue
vt

Problem solving techniques:

Pseudocode: is a detailed yet readable description of what a computer program must do, expressed in a
formally-styled natural language rather than in a programming language. Pseudocode is sometimes used
as a detailed step in the process of developing a program. It allows designers or lead programmers to
express the design in great detail and provides programmers a detailed template for the next step of
writing code in a specific programming language.

Algorithm: In its purest sense, an algorithm is a mathematical process to solve a problem using a finite
number of steps. In the world of computers, an algorithm is the set of instructions that defines not just
what needs to be done but how to do it. In an algorithm,

• Each step should be numbered in a hierarchical manner,


• Every step must be complete, unambiguous and error free .

Flow Chart: A flowchart is a diagram that describes a process or operation. It includes multiple steps,
which the process "flows" through from start to finish. Common uses for flowcharts include developing
business plans, defining troubleshooting steps, and designing mathematical algorithms.

m
co
e.
dg
ue
vt
m
co
e.
dg

1. Write an algorithm to compute the area and perimeter of a circle.


Step 1: Start
ue

Step 2: Read r
Step 3: a= 3.142*r*r
p= 2* 3.142*r
Step 4: Print a, p
Step 5: Stop
vt

2. Write an algorithm to compute the area and perimeter of a rectangle.


Step 1: Start
Step 2: Read l, b
Step 3: a= l*b
p= 2* (l + b)
Step 4: Print a, p
Step 5: Stop

3. Write an algorithm to compute the perimeter and area of a triangle.


Step 1: Start
Step 2: Read a, b, c
Step 3: s= (a + b + c)/2
a= sqrt(s*(s-a)*(s-b)*(s-c))
p= a + b + c
Step 4: Print a, p
Step 5: Stop

4. Write an algorithm to compute the compound interest.


Step 1: Start
Step 2: Read P, T, R
Step 3: CI= P*(1+R/100)T-P
Step 4: Print CI
Step 5: Stop

5. Write an algorithm to simulate simple calculator or to perform arithmetic operations.

m
Step 1: Start
Step 2: Read n1, n2
Step 3: sum = n1 + n2
sub = n1 - n2

co
mul = n1 * n2
div = n1 / n2
Step 4: Print sum, sub, mul, div
Step 5: Stop

6. Write an algorithm to calculate the area and volume of sphere.


Step 1: Start
e.
Step 2: Read r
Step 3: A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r
dg
Step 4: Print A, V
Step 5: Stop

7. Write an algorithm to calculate the area and volume of cube.


Step 1: Start
Step 2: Read s
ue

Step 3: A= 6*s*s
V= s*s*s
Step 4: Print A, V
Step 5: Stop
vt

8. Write an algorithm to convert degrees in Fahrenheit to degrees in Celsius.


Step 1: Start
Step 2: Read f
Step 3: c=(5/9)*(f-32)
Step 4: Print c
Step 5: Stop
1. Draw the flowchart to compute Simple Interest.

Start

Read P, T, R

SI= (P*T*R)/100

m
Print SI

Stop

co
2. Draw the flowchart to compute the area and perimeter of a circle.

Start
e.
Read r
dg
A = 3.142*r*r
P = 2* 3.142*r

Print A, P
ue

Stop
vt

3. Draw the flowchart to compute the area and perimeter of a rectangle.

Start

Read l, b

A = l*b
P = 2*(l + b)

Print A, P
Stop

4. Draw the flowchart to compute the area and perimeter of a triangle when three sides are given.

Start

Read a, b, c

m
s = (a + b + c)/2
A = sqrt(s*(s-a)*(s-b)*(s-c))
P=a +b + c

co
Print A, P
e. Stop

1. Draw the flowchart to simulate the simple calculator.


dg

Start

Read n1, n1
ue

sum=n1+n2
sub=n1-n2
mul=n1*n2
div=n1/n2
mod=n1%n2
vt

Print sum, sub, mul, div,mod

Stop

2. Draw the flowchart to compute Compound Interest.

Start

Read P, T, R

CI= P*(1+R/100)T-P
Print CI
Stop

1. Draw the flowchart to compute the area and volume of sphere.


Start

m
Read r

co
A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r
e. Print A, V

Stop
dg

1. Draw the flowchart to compute the area and volume of cube.


Start

Read s
ue

A= 6*s*s
V= s*s*s
vt

Print A, V

Stop
1. Draw the flowchart to convert from degrees in Fahrenheit to degrees in Celsius.

Start

Read f
c=(5/9)*(f-32)

Print c

m
Sto

co
e.
dg
ue
vt
1. Write a Pseudo code for printing the number and its square starting from 4 to 9.
Begin
Input 4
square=4*4
Print 4,16
do the same for each of the other numbers from 5 to 9
End
or
Start with the number 4
Compute its square
Print the number and its square
do the same for each of the other numbers from 5 to 9

m
2. Write a Pseudo code to compute the Simple Interest.
Begin
Input P, T, R
SI= (P*T*R)/100

co
Print SI
End

3. Write a Pseudo code to compute the Compound Interest.


Begin
Input P, T, R
e.
CI= P*(1+R/100)T-P
Print CI
End
dg

4. Write a Pseudo code to calculate area and perimeter of circle.


Begin
Input r
A=3.142*r*r
P=2*3.142*r
Print A, P
ue

End
vt
Write a Pseudo code to calculate the area and perimeter of rectangle.
Begin
Input l, b
A=l*b
P=2*(l+b)
Print A, P
End

6. Write a Pseudo code to calculate the area and perimeter of triangle when three sides are given.
Begin
Input a, b, c
s= (a + b + c)/2
A= sqrt(s*(s-a)*(s-b)*(s-c))

m
P= a + b +c
Print A, P
End

7. Write a Pseudo code to calculate the area and perimeter of sphere.

co
Begin
Input r
A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r
Print A, V
End
e.
8. Write a Pseudo code to calculate the area and perimeter of cube.
Begin
Input s
dg

A= 6*s*s
V= s*s*s
Print A, V
End

9. Write a Pseudo code to convert from degrees in Fahrenheit to degrees in Celsius.


ue

Begin
Input f
c=0.56*(f-32)
Print c
End
vt
Introduction to C :

m
co
e.
C is a general purpose, procedural, structured computer programming language developed by
Dennis Ritchie 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.
dg

Characteristics of C

 C is a robust language whose rich set of built-in functions and operators can be used to write
ue

complex programs. The C compiler combines the features of assembly languages and high-level
languages, which makes it best suited for writing system software as well as business packages.

Some basic characteristics of C language that define the language and have led to its popularity as a
programming language are listed below:
vt

a high-level programming language, which enables the programmer to concentrate on the


problem at hand and not worry about the machine code on which the program would be run.

to learn as compared to other


languages.

ming approach, C enables users to


think of a problem in terms of functions/modules where the collection of all the modules makes up
a complete program. This feature facilitates ease in program debugging, testing, and maintenance.

treated as an integer and vice


versa).

code can be organized as a collection of one or more functions

program written in any other language.

-level programming.

m
Perl, etc) are based on C.

run on another

co
compute with little or no modification.

e.
dg
4.3 Uses of C

C is a very simple language that is widely used by software professionals around the globe. The
uses of C language can be summarized as follows:
ue

stem programming. The portability, efficiency, the ability to access


specific hardware addresses and low runtime.

rogramming languages are often implemented


in C. For portability and convenience reasons, C is sometimes used as an intermediate language for
vt

implementation of other languages. Major parts of popular operating systems like windows, UNIX,
Linux are still written in C.

-user applications.

ike cellular phones and palmtops consisting of microprocessor, operating system


and some applications are written in C.

chines and digital cameras are


consisting of many programs which are written in C language.

ar gaming frameworks have been built


using C language.
Basic Concepts of a C Program or Structure of a C Program

The basic concepts of a C program can be explained by writing the structure of a C program. The
structure of a C program is nothing but the rules that are to be followed while writing a C program.

The structure of a C program is shown below:

m
co
1.Comments

At the beginning of each program is a comment with a short description of the problem to

be solved.
e.
dg

Ex: 1. /* Program1: To find the sum of two numbers*/

2. // Program2: To calculate the area and perimeter of circle

symbol /* and ends with */ represents the multiline comment.


ue

2. Preprocessor directives

The preprocessor statements start with # symbol.


vt

include some of the files in the beginning of the

program.

Ex: #include<stdio.h>

#include<math.h>

are the files that the compiler includes in the beginning of the program.

perform

standard input and output ‗stdio‘ operations.


The ‗#include‘ directive tells the compiler that we will be using parts of the standard

function library.
.h says this file is a header file.

Ex: #define PI 3.142

3. Global Declarations

iables that are declared above (before) the main program are called global variables.

m
functions.

4. Function declarations and Definitions

co
this section the functions are declared.

5. The program header: main()


e.
6. Body of the program
dg

statements which comprise the ‗body‘- this is called the action portion of the program.

Ex: #include<stdio.h>
ue

main()

/* action portion of the program*/


vt

1. Declaration section

2. Executable section

 Declaration section

section.

e declaration shown below:


int sum=0;

int a;

float b;

Here, the variable sum is declared as an integer variable and it is initialized to zero. The variable

a is declared as an integer variable whereas the variable b is declared as a floating point

variable.

 Executable section

The instructions

m
can be input/output statements, expressions to be evaluated, simple assignment statements, control
statements such as if statement, for statement etc.Each executable statement ends with ―;‖.

Example: Write a C program to display ―Hello World‖.

co
#include<stdio.h>

void main()

{
e.
printf(―Hello World‖);

}
dg

Files used in a C Program

A C program uses four types of files as follows:


ue
vt

1. Source Code File

ontain other source code files.


2. Header Files

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.

m
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,

co
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.

Standard header files


e.
dg
Common standard header files are:

– used for handling string functions.

– used for handling string functions.


ue

– used for some miscellaneous functions.

– used for giving standardized input and output.

– used for mathematical functions.


vt

– used for dynamic memory allocation.

– used for clearing the screen.

e 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
binary code of the function definitions.

files together. It has a '.o' extension.

4. Executable file

object files are linked by the linker for producing a binary file which will be

m
executed directly.

co
Compiling and Executing C Programs
e. e that consists of the statements of the

program written in C language. This source file usually contains ASCII characters and can be
dg

produced with a text editor, such as Windows notepad, or in an Integrated Design Environment.

processed by a special program called a compiler.


ue

system API (Application Programming Interface).


vt

However, even the object file is not an executable file. Therefore, in the next step, the object

file is processed with another special program called a linker.

e, the same linker is used for


object files regardless of the original language in which the new program was written. The output of
the linker is an executable or runnable file. The process is shown in Figure 4.3.
In C language programs, there are two kinds of source files. In addition to the main (.c) source file,
which contains executable statements there are also header (.h) source files.

m
 Every C program uses standard header files, which are written as part of the source code for
modular C programs.

co
 The compilation process shown in Figure 4.4 is done in two steps.

 In the first step, the preprocessor program reads the source file as text, and produces another text
file as output. The output of the preprocessor is a text file which does not contain any
e.
preprocessor statements. This file is ready to be processed by the compiler.
dg
ue

 The linker combines the object file with library routines (supplied with the compiler) to produce
the final executable file.

 In modular programming, the source code is divided into two or more source files. All these
vt

source files are compiled separately thereby producing multiple object files.

 These object files are combined by the linker to produce an executable file (Figure 4.5).
m
co
Using Comments

r the purpose of the file code is not clear to the reader.


e.
the reader understand the code clearly.
dg

is merely an internal program documentation.

The compiler ignores the comments when forming the object file means that the comments

are non-executable statements.


ue

C supports two types of comments.

// is used to comment a single statement. This is known as a line comment. A line comment

can be placed anywhere on the line and it does not require to be specifically ended as the end of
vt

the line automatically ends the line.

/* is used to comment multiple statements. A /* is ended with */ and all statements that lie

within these characters are commented. This type of comment is known as block comment.

C Tokens

nstructed using a combination of these tokens.


m
1. Keywords:

cannot be changed by the user.

co
keywords are basically a sequence of characters that have a fixed meaning.
e.
int, float, if, while, void etc are valid keywords.

Int, Float, IF, VOID etc are invalid keywords. (They are written using capital letters).
dg

List of keywords:
ue
vt

2. Variables: A variable is a data item whose value changes during the execution of program.

Ex: int a,b,sum;

3. Constants: A constant is a data item which will not change during the execution of a

program.

Ex: #define PI 3.142


4. Strings: String is an array of characters and terminated by NULL character which is denoted
by

‗\0‘.

Ex: char name[21];

5. Operators: Operator is a symbol (or token) that specifies the operation to be performed on

various types of data.

Ex: Arithmetic operators (+,-,*,/), Relational operators (&&,||,!), Logical operators ( >,>=,<,<=)

and Assignment operator (=) etc.

m
6. Special characters: [ ], { }, ( ) etc. used in the program to execute the code correctly and helps

to write a complex codes by special symbols

CHARACTER SET IN C :

co
character set that defines the

fundamental units used to represent information.


e.
represent information.

that act as basic building blocks of a C


dg

program.

a. English alphabet: Include both lower case (a z) as well as upper case (A Z) letters
ue

b. Digits: Include numerical digits from 0 to 9

c. Special characters: Include symbols such as, % & ) < > * S / ) [ " etc.,

d. White space characters: These characters are used to print a blank space on the screen.

They are shown in Figure 4.6.


vt
m
e. Escape sequence: ‗\n‘ is an escape sequence and represents a newline character. It is used to

co
print the message on a new line on the screen. Like the newline character, the other escape

sequences supported by C language are shown in Table 4.1


e.
dg
ue
vt

4.10 Identifiers

Identifiers help us to identify data and other objects in the program.

functions.

Rules for Forming ldentifier Names:

Some rules have to be followed while forming identifier names. They are as follows:
except the underscore ‗_‘.

nnot be two successive underscores.

‗FIRST‘ is different from ‗first‘ and ‗First‘.

character must be avoided because several compiler-defined identifiers in the standard C library

m
have underscore as their first character.

be of any reasonable length. They should not contain more than 31 characters.

co
They can actually be longer than 31, but the compiler looks at only the first 31 characters of the

name.

Examples of valid identifiers include:


e.
roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code, DeptCode, RollNo,

EMP_NO

Examples of invalid identifiers include:


dg

23 student, %marks, @name, #emp_number, basic.pay, -HRA, (DA), &dept_code, auto

Procedure to create a C program


There are basically three steps involved in creating and executing a c program.
1. Creating a source code in the form of text file acceptable to the compiler.
ue

a. Open an operating system supported editor in the computer.


Ex: gedit filename.c
b. Editor is a place where we write all the computation procedure in the form of instructions which is
called as the source code.
c. The file that contains the source code must be saved with the extension ―.C‖.
vt

2. Invoking the compiler to process the source code and produce an object file.
a. During this process the compiler checks for the errors and gives the platform to debug the errors if
exists, if there exists no errors compiler converts source code into machine understandable language
and stores as object file with the ―.O‖ extension using the command : gcc filename.c –o filename –
lm OR gcc filename.c
3. Linking all the object files and libraries to produce an executable file.
a. In this step all the object files, libraries and header files are linked to produce an executable file.
b. The executable file contains a set of instructions understood by the computer.
c. This executable file is executed using a command ./a.out or ./filename to get the desired output.

The following diagram summarizes the steps


m
Example programs:

co
1. A C program to print “WELCOME TO JIT”.

#include<stdio.h>

void main()
{
e.
printf(―\n WELCOME TO JIT‖);
}

2. A C program to add 2 integer numbers.


dg

#include<stdio.h>

void main()
{
int a,b,c;
ue

printf(―\n Enter the value of a:‖);


scanf(―%d‖,&a);
printf(―\n Enter the value of b:‖);
scanf(―%d‖,&b);
c=a+b;
printf(―\n The addition of 2 numbers is:%d‖,c);
vt

}
3. A C program to calculate the circumference and area of a circle.

#include<stdio.h>

void main()
{
float r,area,circum;
printf(―\n Enter the value of radius:‖);
scanf(―%f‖,&r);
circum=2*3.142*r;
area=3.142*r*r;
printf(―\n The circumference of a circle is: %f‖,circum);
printf(―\n The area of a circle is:%f‖,area);
}
4. A C program to calculate the Simple Interest

#include<stdio.h>

void main()
{
float p,t,r,si;
printf(―\n Enter the values of p,t and r values‖);
scanf(―%f%f%f‖,&p,&t,&r);
si=(p*t*r)/100;
printf(―Simple Interest=%f‖,si);
}

m
5. A C program to calculate the area of triangle by using the values of sides of a triangle.

#include<stdio.h>
#include<math.h>

co
void main()
{
float area,a,b,c,s;
printf("Enter the values for its sides a,b,c:\n");
scanf("%f%f%f",&a,&b,&c);
s=(a+b+c)/2;
e.
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("\n The area of the triangle=%f \n",area);
}
dg

6. A C program to calculate the area of triangle by using Length and breadth

#include<stdio.h>
#include<math.h>
ue

void main()
{
float area,l,b;
printf("Enter the values for l and b:\n");
scanf(―%f%f‖,&l.&b);
area=0.5*l*b;
vt

printf(― Area of Triangle=%f‖,area);


}
7. A C program to print largest of 2 numbers.

#include<stdio.h>

void main()
{
int a,b;
printf(―\n Enter the values of a and b:‖);
scanf(―%d%d‖,&a,&b);
if(a>b)
{
printf(―\n A is largest―);
}
else
{
printf(―\n B is largest‖);
}
}
8. A C program to determine whether the given number is positive or negative.

#include<stdio.h>

void main()
{

m
int num;
printf("\n Enter the number:\n");
scanf("%d",&num);
if(num>0)
printf("\n Given number is Positive\n");

co
else
printf("\n Given number is Negative\n");
}
9. A C program to check whether the given number is even or odd.

#include<stdio.h>
e.
void main()
{
int rem,n;
dg

printf("\n Enter the number\n");


scanf("%d",&n);
rem=n%2;//calculate the remainder of the number
if(rem==0)
printf("\n Given number %d is Even number\n",n);
else
ue

printf("\n Given number %d is Odd number\n",n);


}
10. A C program to find biggest of 3 numbers.

#include<stdio.h>
vt

void main()
{
int a,b,c;
printf(―\n Enter the values of a,b and c:‖);
scanf(―%d%d%d‖,&a,&b,&c);
if(a>b && a>c)
{
printf(―\n A is largest―);
}
else if(b>c && b>a)
{
printf(―\n B is largest‖);
}
else
{
printf(―\n C is largest‖);
}
}

Types of C Tokens:
Keywords Ex: if, for, while etc

Identifiers Ex: sum, length, i etc

Tokens Constants Ex: 10, ‗a‘, 10.5 etc

Operators Ex: +,-,*, /

m
Special Symbols Ex: [ ], { }, ( )

1. Keywords:
 Keywords are the tokens which have predefined meaning in C language, whose meaning cannot be

co
changed by the user.
 They are also called reserved words.
 C Keywords are case sensitive. Therefore all C keywords must be written in small letters.
int ,float,if,while,void etc are valid keywords.
e.
Int, Float, IF, VOID etc are invalid keywords. (They are written using capital letters).

List of keywords:
auto double int struct
break else long switch
dg

case enum register typedef


char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
ue

There are total 32 keywords in C language as shown above.

2. Identifiers: Identifiers are the names given to various program elements such as variables, constants, function
names, array names etc.
vt

Ex: int a,b,sum;

3. Constants: A constant is a data item which will not change during the execution of a program.

4. Operators: Operator is a symbol (or token) that specifies the operation to be performed on various types of
data.
Ex: Arithmetic operators (+,-,*,/), Relational operators (&&,||,!), Logical operators ( >,>=,<,<=) and Assignment
operator (=) etc.

5. Special Symbols: [ ], { }, ( ) etc used in the program to execute the code correctly and helps to write a complex
codes by special symbols.

**Data types and Sizes


 The data type defines the type of data stored in a memory location.
 The data type determines how much memory should be allocated for a variable.
 The data types that can be manipulated by machine instructions are called ‗basic or primitive data types‘.
int

char

Basic data types float

double

void
i. int:
 An int is a keyword which is used for defining integers in C language.

m
 Using int the programmer can inform the compiler that the data associated with this should be
treated as integer.
 Using „int‟ compiler determines the size of the data (2 bytes) and reserve space in memory to store
the data.
 Integer data types namely:

co
1. short int 2. int 3.long int

Type Size
short int 2 bytes
int 2 bytes
e. long int 4 bytes
Ex: int a,b,c;

ii. float:
dg

 A float is a keyword which is used to define floating point numbers in C language.


 The programmer can inform the compiler that the data associated with this keyword should be
treated as floating point number.
 The default precision of floating point number is 6 digits after dot(.).
Size of float
16-bit Machine 4 bytes
ue

32-bit Machine 8 bytes

Ex: float x,y,z;

iii. double:
 It is a keyword which is used to define long floating point numbers in C language.
vt

 The default precision of floating point number is 14 digits after dot(.).


Size of double
16-bit Machine 8 bytes
32-bit Machine 16 bytes

Ex: double p,q,r;

iv. char:
 It is a keyword which is used to define single character or a sequence of characters called String in C
language.
 Using this keyword, the compiler determines the size of the data and reserve space in memory to
store the data.
 Each character stored in the memory is associated with a unique value called an ASCII (American
Standards Code for Information Interchange).
Size of char
16/32-bit Machine 1 byte

Ex: char ch; // ch variable stores a single character Ex: ch= ‗a‘;
char s[20]; // s variable stores a string(group of characters) Ex: s= ―jit dvg‖;

v. void:
 It is an empty data type, since no value is associated with this data type.
 It does not occupy any space in the memory.
Size of void

m
16/32-bit Machine 0

Ex: void main( )


{
}

co
Constants
 A constant is a data item which will not change during the execution of a program.
 The constants cannot be modified in the program.
e. Decimal

Integer Octal
dg
Hexadecimal
Numeric
Constant
Fractional form (Ex: 0.56,-9.5)
Floating
Point Exponent form (Ex: 634e-5)
ue

Constants Character Constant (Ex:‗a‘,‘9‘,‘\n‘)

String Constant (Ex:‖ramesh‖,‖9‖)


vt

Backslash Constant (Escape Sequence Character):


 An escape sequence character begins with a backslash and is followed by one character.
 A backslash (\) along with some characters give rise to special print effects by changing (escaping) the
meaning of some characters.
 Backslash characters are normally used during printing using printf() function. These characters will not
appear physically on screen. But when printed they produce special effects.

Escape Character Character Meaning


\t Horizontal tab Cursor moves towards right by 8 positions
\n New line Cursor moves to the beginning of next line
\0 Null Null character
**Declaration, Assignment and Print Statements
Declarations

 „Declaration‟ tells the computer which storage locations or variables to use in the program.
 All variables must be declared before used.
Ex: int a,b,c;
char c;

Initialization
 A variable may also be initialized in its declaration. The name is followed by an assignment operator (=)
sign in an expression.

m
Ex: int i=5;
float pi=3.142;
 A semicolon(;) terminates every complete statement in C and variables are separated by (,) commas.
 The line containg #include does not need (;) because it is a compiler directive, not a C statement.

co
 The main() program header does not need (;) because it is not a complete C statement.

**Variable
 A variable is a name given to a memory location within the computer that can hold one value at a
e.
time.
OR
A variable is a data item whose value changes during the execution of program.
dg

 Every variable should be associated with type, size and value.


 Whenever a new value is placed into a variable, it replaces the previous value.

**Rules for defining variables (or Identifiers)


ue

 The first character in the variable should be a letter (A to Z or a to z) or an underscore.


 The first character can be followed by any number of letters or digits (0 to 9) or underscores.
 No extra symbols are allowed other than letters, digits and underscore.
 The length of an identifier (variables/constants) can be up to maximum of 31 characters.
vt

 C keywords should not be used as variable names.


 The variable name should not begin with a digit or any other special characters other then
underscore.
Ex: Classify the following into valid and invalid variable names in C. If invalid give reasons:

Variable Valid/Invalid Reason


principle_amount Valid
A Valid
Sum1 Valid
for1 Valid
If Invalid It is a keyword
For Invalid It is a keyword
3_factorial Invalid Should not start with digit
Sum,1 Invalid Comma should not be there
sum-of-digits Invalid Minus sign should not be there
sum_of_digits Valid
sum of digits Invalid No spaces are allowed
$sum Invalid $ sign should not be there
sum= Invalid = sign should not be there
one+two Invalid + sign should not be there
sum! Invalid ! sign should not be there
Int Invalid It is a keyword
$roll no Invalid $ sign should not be there
_name1 Valid
James bond Invalid No spaces are allowed

m
Declaring/Defining a Variable

 It is a method of informing the compiler to reserve the memory space for the program data based on
the type of variables.

co
Syntax: datatype v1,v2,…….,vn ;

Where datatype: it can be int, float,char, double etc.


e.
v1,v2,---,vn: is a list of variables, which are separated by commas.

Ex: int a,b,c;


float p,t,r,si;
dg

Initializing the variables


 Initialization is the process of assigning values to the variables.
Syntax:
datatype var_name=data;
ue

 datatype: is the type of the data to be stored in memory location. (int,float,char,double)


 var_name: name of a variable
 = is assignment operator
 Data: is the value to be stored in memory associated with variable var_name.
Ex: int a=10;
vt

**Operators and Expressions


 Operator: Operator is a symbol (or token) that specifies the operation to be performed on various
types of data.
 Operand: A variable or a value on which the operation is performed is an operand.
 Expression: A sequence of operands and operators that reduces to a single value is an expression.
Operands

a + b Expression
a b
_

Operators
Classification of operators
The operators in C can be classified based on:
 The number of operands an operator has.
 The type of operation being performed.

1. Classification of operators based on the number of operands


Unary operators Ex: ++,-- etc.

Operators Binary operators Ex: +,-,*,/ etc.

Ternary operators Ex: ? and :

m
i) Unary operator: An operator which acts on only one operand to produce the result is called Unary
operator.
Ex: -10,-a,*b,++a,a++,b-- etc.

co
ii) Binary operator: An operator which acts on two operands to produce the result is called Binary
operator.
Ex: a+b, a*b, 10/5 etc
iii) Ternary operator: An operator which acts on three operands to produce the result is called
Ternary operator.
Ex: a ? b : c;
e.
2. ***Classification of operators based on type of operation
Arithmetic Operators Ex: +, - , * etc.
dg

Assignment Operators Ex: =, +=

Increment/Decrement Operators Ex: ++, --

Relational Operators Ex: <, >, <=, >=


ue

Types of Operators Logical Operators Ex: &&, ||

Conditional Operators Ex: ?:


vt

Bitwise Operators Ex: &, ^

Special Operators Ex: , , . , [ ] , ( )

i) Arithmetic Operators
 The operators that are used to perform arithmetic operations such as addition, subtraction,
multiplication, division and modulus are called arithmetic operators.
 These operators perform operations on two operands and hence they are called binary operators.
Operator Symbol Example Result
Addition + 4+2 6

Subtraction - 4-2 2

Arithmetic Operators Multiplication * 4*2 8

Division / 4/2 2

Modulus % 4%2 0
(Remainder)
 % (modulus operator) divides the first operand by second and returns the remainder.
 % (modulus operator) cannot be applied to floating or double.

m
 % operator returns remaining value (remainder) of an integer division.
ii) Assignment Operators
 An operator which is used to assign the data or result of an expression into a variable (also called
memory location) is called an assignment operator.

co
 Assignment operator is denoted by ‗=‘ sign.
Ex: a=b; //value of b is copied into variable a

Types of Assignment statements


a). Simple Assignment Statement
e.
variable= expression;

Ex: a=10;
dg
a=b;
a=a+b;
Area= l*b; //Result of Expression l*b is copied into variable area.
b). Shorthand Assignment Statement
 The operators such as +=, -=, *=, /= and %= are called shorthand assignment operators.
Ex 1: a=a+10; // simple assignment
ue

a+=10; // shorthand assignment


Ex 2: i=i+2;
i+=2;
 If expr1 and expr2 are expressions then
expr1 op = expr2 ;
vt

is equivalent to
expr1 = (expr1) op (expr2) ;
i.e., x*=y+1 means x=x*(y+1) ;

c). Multiple Assignment Statement


 Assigning a value or a set of values to different variables in one statement is called multiple assignment
statement.
 The multiple assignments are used whenever same value has to be copied into various memory locations.

Ex: int i=10; //simple assignment


int j=10;
int k=10;
int i=j=k=10; //multiple assignment

iii) Increment and Decrement Operators


Increment Operator
 „++‟ is an increment operator. This is unary operator. It increments the value of a variable by one.
Post Increment Ex: a++
Increment
Operator Pre Increment Ex: ++a

1. Post Increment
 It increments the value after (post) the operand value is used. i.e., operand value is used first and

m
then the operand value is incremented by 1.
Ex: void main()
{
int a=20,b; // a=20, b?
b=a++; // b=a=20, a=a+1= 20+1

co
printf(―%d‖,a); // a=21
printf(―%d‖,b); // b=20
}

2. Pre Increment
 It increments before (pre) the operand value is used. The operand value is incremented by 1 and this
e.
incremented value is used.
Ex: void main()
{
int a=20,b; // a=20, b?
dg

b=++a; // a=++a=a+1= 20+1, b=a=21


printf(―%d‖,a); // a=21
printf(―%d‖,b); // b=21
}

Decrement Operator
ue

 '--' is a decrement operator. This is a unary operator. It decrements the value of a variable by one.
Post Decrement Ex: a--
Decrement
Operator Pre Decrement Ex: --a

1. Post Decrement
vt

 It decrements the value after (post) the operand value is used. i.e., operand value is used first and
then the operand value is decremented by 1.
Ex: void main()
{
int a=20,b; // a=20, b?
b=a--; // b=a=20, a=a-1= 20-1
printf(―%d‖,a); // a=19
printf(―%d‖,b); // b=20
}
2. Pre Decrement
 It decrements before (pre) the operand value is used. The operand value is decremented by 1 and
this decremented value is used.
Ex: void main()
{
int a=20,b; // a=20, b?
b=--a; // a=--a=a-1= 20-1, b=a=19
printf(―%d‖,a); // a=19
printf(―%d‖,b); // b=19
}
Eg:
Initially a=10, b=5, c=20 simplify the following expression
W = a++ + ++b + c++ - ++a
= 10 + 6 + 20 - 12
a=11 b=6 c=21 a=12

w = 24

a=12 , b=6, c=21, w=24

m
i. X = --a + b-- + ++c – a++ - --b
= 9 + 5 + 21 - 9 - 5
a=9 b=4 c=21 a=10 b=5
= 21

co
a= 10 b= 5 c= 21 x= 21

iv) Relational operators


 The operators that are used to find the relationship between two operands are called relational
operators.
e.
 The relationship between the two operand values results in true (always 1) or false (always 0).
Relational operators available in C are:
dg
ue
vt

 All the relational operators are having a same priority and left to right associativity.
 The relational operators have lower precedence than arithmetic operators.

Equality operators
 C supports two kinds of equality operators to compare their operands for strict equality or inequality.
equal ==
not equal ! =
 Equality operators have lower precedence than the relational operators.
Eg: a=10, b=6
i. C=a>b
C=10>6  10 is greater than 6 so the operator returns value 1, indicating true
C=1
ii. C=a<b
C=10<6  10 is not less than 6, so the operator returns value 0, indicating false
C=0
iii. C=a>=b
C=10>=6
C=1
iv. C=a<=b
C=10<=6
C=0
v. C=a==b
C=10==6  ==checks whether 10 is equal to 6, if equal return 1, else returns 0
C=0

m
vi. C=a!=b
C=10!=6  != checks whether 10 is not equal to 6, if not equal returns 1, else returns 0
C=1

co
v) Logical operators
 The operators that are used to combine two or more relational expressions are called logical
operators.
 The output of relational expression is true or false, the output of logical expression is also true or
false.
e.
Logical operators available in C:
Operators
not !
dg

and &&
or ||

O perand1 Operand2 AND(&&) OR(||) NOT(!) (Operand1)


T True(1) True(1) True(1) True(1) False(0)
Tr True(1) False(0) False(0) True(1) False(0)
ue

F False(0) True(1) False(0) True(1) True(1)


Fa False(0) False(0) False(0) False(0) True(1)

Logical NOT: The logical NOT operator is denoted by ‗!‘. The output of not operator can be true or false. The
result is true if the operand value is false and the result is false if the operand is true.
vt

Logical AND: The logical AND operator is denoted by ‗&&‘. The output of and operator is true if both the
operands are evaluated to true. If one of the operand is evaluated false, the result is false.

Logical OR: The logical OR operator is denoted by ‗||‘. The output of or operator is true if and only if at least one
of the operands is evaluated to true. If both the operands are evaluated to false, the result is false.

Ex:
i. Given A=10, Evaluate C=!A
A=10  other than value 0, any value is treated as 1. So, A=1
C = !A
C = !1
C=0
ii. Given A=10, B=15, Evaluate C = A&&B
A=10  treated as A=1 (Because other than value 0, any value is treated as 1)
B=15  treated as B=1 (Because other than value 0, any value is treated as 1)
C = A&&B
= 1 && 1
C= 1
iii. Given A=20, B=25, Evaluate C = A || B
A = 20  treated as A=1 (Because other than value 0, any value is treated as 1)
B = 25  treated as B=1 (Because other than value 0, any value is treated as 1)
C = A || B
= 1 || 1
C=1

vi) Conditional Operator


 The conditional operator is also called as 'ternary operator'.

m
 An operator that operates on the three operands is called ternary operator.
Syntax:
(expr1)? expr2: expr3;

co
Where,
- expr1 is evaluated first.
- If expr1 is evaluated to true, then expr2 is evaluated.
- If expr1 is evaluated to false, then expr3 is evaluated.
e.
Example:
1. Write a C program to find the biggest of two numbers using conditional operator.
#include<stdio.h>
dg

void main()
{
int a,b,big;
printf(―Enter the values of a and b:‖);
scanf(―%d%d‖,&a,&b);
big=(a>b)?a:b;
ue

printf(―Big=%d‖,big);
getch();
}

2. Write a C program to find the smallest of two numbers using conditional operator.
vt

#include<stdio.h>
void main()
{
int a,b,small;
printf(―Enter the values of a and b:‖);
scanf(―%d%d‖,&a,&b);
small=(a<b)?a:b;
printf(―Small=%d‖,big);
getch();
}

vii) Bitwise Operators


 The operators that are used to manipulate the bits of given data are called bitwise operators.

Bitwise operators available in C are:


Operator
Bit-wise Negate ~

Left Shift <<

Right Shift >>


Bitwise Operators
Bit-wise AND &

Bit-wise XOR ^

m
Bit-wise OR |
 These may only be applied to integral operand. i.e., char, short, int and long whether signed or unsigned.

co
a. Bit-wise Negate or One‟s Complement(~)
 The operator that is used to change every bit from 0 to 1 and 1 to 0 in the specified operand is called
One‟s complement operator.

Truth table of One‟s Complement(~):


e.
Op1 ~Op1
0 1
1 0
dg

 One‘s complement operator is denoted by ‗~(tilde)‘ symbol.

Ex:
i. Let A= 15, Evaluate B = ~A
Convert A = 15 to binary representation and apply Bitwise Negate to binary values
ue

Binary Representation (8 bit representation)


15 = 0 0 0 0 1 1 1 1
240 = 1 1 1 1 0 0 0 0

Write a C program to show the usage of Bitwise Negate operator.


vt

#include<stdio.h>
void main()
{
int a=10,b;
b=~a;
printf(―~%d=%d‖,a,b);
}

Output: ~10=245
Binary Representation(8 bit representation):
10 = 0 0 0 0 1 0 1 0
245= 1 1 1 1 0 1 0 1

b. Left shift operator (<<)


 The operator that is used to shift the data by a specified number of bit positions towards left is called
„left shift operator‟.
Syntax:
b=a<<num;

i. Ex: Let a=5, Evaluate b = a<<1

MSB is discarded

0 0 0 0 0 1 0 1 a=5

m
b=10
0 0 0 0 1 0 1 0

0 is appended at LSB

co
b = 10

Write a C program to show the usage of Left Shift operator.


#include<stdio.h>
void main()
{
e.
int a=5,b;
b=a<<1;
printf(―%d<<1=%d‖,a,b);
}
dg

Output: 5<<1 = 10

c. Right shift operator (>>)


 The operator that is used to shift the data by a specified number of bit positions towards right is
called „right shift operator‟.
Syntax:
ue

b=a>>num;

Ex:
i. Let a=10, Evaluate b = a>>1
LSB is discarded
vt

0 0 0 0 1 0 1 0 a=10

0 0 0 0 0 1 0 1 b=5
0 is appended at MSB
b=5
Write a C program to show the usage of Right Shift operator.
#include<stdio.h>
void main()
{
int a=10,b;
b=a>>1;
printf(―%d>>1=%d‖,a,b);
}
Output: 10>>1=5

. Bit-wise AND (&)


 If the corresponding bit positions in both the operands are 1, then AND operation results in 1,
otherwise AND operation results in 0.

Truth table of Bit-wise AND (&):

Op1 Op2 O p1&Op2


0 0 0
0 1 0
1 0 0
1 1 1

m
Ex:

Let a=10 and b=6. Evaluate c = a & b

co
Binary Representation: (8 bit representation)
10 = 0 0 0 0 1 0 1 0
06 = 0 0 0 0 0 1 1 0
02 = 0 0 0 0 0 0 1 0
C =2
e.
Write a C program to show the usage of ‗&‘ operator.
#include<stdio.h>
void main()
{
dg
int a=10,b=6;
c=a&b;
printf(―%d&%d=%d‖,a,b,c);
}
Output: 10&6=2
ue

e. Bit-wise OR (|)
 If the corresponding bit positions in both the operands are 0, then OR operation results in 0,
otherwise OR operation results in 1.

Truth table of Bit-wise OR (|):


vt

Op1 Op2 Op1|Op2


0 0 0
0 1 1
1 0 1
1 1 1

Ex:
Let a=10, b=6. Evaluate c = a | b

Binary Representation: 10 = 0 0 0 0 1 0 1 0
06 = 0 0 0 0 0 1 1 0
14 = 0 0 0 0 1 1 1 0
C=14
Write a C program to show the usage of ‗|‘ operator.
#include<stdio.h>
void main()
{
int a=10,b=6;
c=a|b;
printf(―%d|%d=%d‖,a,b,c);
}

Output: 10|6=14

f. Bit-wise XOR (^)

m
 If the corresponding bit positions in both the operands are different, then XOR operation results in
1, otherwise XOR operation results in 0.
0^0=0
0^1=1
1^0=1

co
1^1=0
Ex:
Let a = 10 and b = 6. Evaluate c = a^b
Binary Representation:
10 = 0 0 0 0 1 0 1 0
e.
06 = 0 0 0 0 0 1 1 0
12 = 0 0 0 0 1 1 0 0
C= 12

Write a C program to show the usage of ‗^‘ operator.


dg

#include<stdio.h>
void main()
{
int a=10,b=6;
c=a^b;
printf(―%d^%d=%d‖,a,b,c);
ue

getch();
}

Output: 10^6=12
vt

viii) Special Operators


 Comma operator, size of operator and [ ], ->, Indirection operator, *, dot operator etc.

i) Comma operator
 Comma Operator has the least precedence among all the operators and it is left associative operator.
 Comma Operator is used in the declaration to separate the variables.
Ex: int a,b,c;
 It can be used to separate the items in the list.
Ex: a=12,345,678;
 It can be used to combine two or more statements into a single statement.
Ex: sum=a+b,sub=a-b,mul=a*b,div=a/b,mod=a%b;

ii) sizeof()
 ‗sizeof()‘ operator is used to determine the number of bytes occupied by a variable or a constant in the
memory.
 Ex: sizeof(char) 1 byte
sizeof(int) 2 bytes
sizeof(float) 4 bytes

Arithmetic Expressions
 The expression consisting of only arithmetic operators such as +, -, *, / and % are called arithmetic
expressions.

Example: Write the equivalent C expression for the Mathematical expressions.

m
Mathematical Expression C Equivalent Expression
S=(a + b +c) /2

( )( )( ) area=sqrt(s*(s-a)*(s-b)*(s-c))

co
x=sqrt(2*3.142*n)
a/b

x=-b/(2*a)
e.
a*x*x+b*x+c
dg
ue
vt

Precedence and Associativity


Precedence of operators or Hierarchy of Operators
 The order in which the different operators are used to evaluate an expression is called Precedence
or hierarchy of operators.

The associativity of operators


 If all the operators in an expression have equal priority, then the direction order chosen (left to right
evaluation or right to left evaluation) to evaluate an expression is called associativity of operators.
 They are classified into two categories based on the direction of evaluation chosen as shown below:
Left to Right Associativity(Left associative)
Ex: All binary arithmetic, logical and relational
Associativity of operators operators etc.

Right to Left Associativity(Right associative)


Ex: assignment operator, unary operator etc.
Left to Right Associativity: In an expression, if there are two or more operators having the same priority and
are evaluated from left-to-right, then the operators are called Left to Right associative operators. We normally
denote using L R. They are also called Left associative operators. This process of evaluating from left to
right is called left associtivity.
Ex: 8+4+3=15
8-4-3=1
In this example, the operators ―+‖ and ―-― are left associative operators.

m
Right to Left Associativity: In an expression, if there are two or more operators having the same priority and
are evaluated from right-to-left, then the operators are called Right to Left associative operators. We normally
denote using R L. They are also called Right associative operators. This process of evaluating from right to
left is called right associtivity.

co
Ex: i=j=k=10.
Precedence and Associativity Chart

Precedence Operators Associativity


1 Innermost brackets or () LR
e.
function call,
Array index reference []
2 Unary operators ++ , -- , ! , sizeof , ~ R L
3 Member Access  LR
dg
4 *, / ,%
Arithmetic operators L R
5 +, -
6 Shift operators << , >> LR
7 Relational operators < , > ,<= , >= LR
8 Equality operators == , != LR
9 Bitwise AND & LR
ue

10 Bitwise XOR ^ LR


11 Bitwise OR | LR
12 Logical AND && LR
13 Logical OR || LR
14 Conditional ?: RL
15 Assignment operators RL
vt

= , += , -= , *= , /=
,%=
16 Comma operator , LR
vt
ue
dg
e.
co
m
Evaluate the expression 100/20<=10-5+100%10-20==5>=1!=20.

m
co
e.
dg
ue
vt
m
co
e.
dg
ue
vt

**Type Conversion
 The process of converting the data from one data type to another data type is called Type
Conversion.
Implicit Conversion 1/2.0 1.0/2.0=0.5000
Type
Conversion Explicit Conversion 1/(float)2 1.0/2.0=0.5000

 C compiler converts the data type with lower rank to the data type with higher rank. This process of
conversion of data from lower rank to higher rank automatically by the C compiler is called
“Implicit type Conversion”.

char short int int unsigned int long int float double
Lower Rank Higher Rank
Data types Data types

m
 If one operand type is same as that of other operand type, no conversion takes place.
Ex: int + int = int, float + float = float
 If one operand type is ‗int‘ and other operand type is ‗float‘, then the operand with type int is promoted to

co
‗float‘ (because float is up in ladder compared with int).
 The programmer can instruct the compiler to change the type of the operand from one data type to
another data type. This forcible conversion from one data type to another data type is called
e.
“Explicit type Conversion” (Type Casting).
Syntax:
(type) Expression
dg

Ex: (int) 9.43


i= (int) 5.99 / (int) 2.4, now it becomes 5/2 = 2, i=2
(float) (3/10) = 3.0 / 10.0 = 0.3
ue

Formatted Output Function: print statement


 The data stored in memory locations has to be converted into appropriate data type and then it is displayed
on the screen for human understanding in the proper format. This can be done by ―printf statement‖.
vt

 Print and Format: The function printf (print+f) prints the data in the specified memory location or
variables after “formatting” the data.
printf(): print format
 There are two simple forms of printf:
1. One that has just a literal string (a sequence of characters within quotation marks)
General form: printf (“……….”);
literal string
Ex : printf (―welcome to jit‖);
Literal string is placed within a parenthesis. The symbols within that string are printed.
2. One that has values of one or more expressions to be printed.
General form : printf (“………” , ……);
(i) (ii)
(i) Control String, including conversion characters
(ii) list of variables or expressions to be printed.
Ex: printf (― %d%f%c‖ , x,y,z);

Format specifiers list of variables.

m
**Guidelines/Rules for printf()
 A printf() always contains a string or format string in quotation marks.
 The control string may or may not be followed by some variables or expressions whose value we want
printed.

co
 Each value to be printed needs a ‗conversion specification‘ like %d to hold its place in the control string.
 This conversion specification describes the exact way the value is to be printed.
 When printf() is executed each conversion specification is replaced by the value of the corresponding
e.
expression, then print according to the rules in specification.
 The symbols \n or \t in control string tell the machine to skip to new line or tab. It affects the appearance of
the output but not displayed as part of it.
dg

 A word or blank space or punctuation symbols within the control string will print exactly as it appears.
 If there are variables or expressions to be printed, commas are used to separate them from the control string
and each other, once comma is used as separator, it is not necessary to add blank spaces (not allowed).
ue

Ex: printf (―%d%d \n‖,a,b);


and Both are same
printf (―%d%d \n‖, a, b);

Control String or Newline character Variables to be printed


Format Specifiers
vt
Format specifiers used in printf()

Data type Format specifier Description


int %d data is displayed as decimal signed integer
%o data is displayed as octal integer
%x or %X data is displayed as hexadecimal integer
%u data is displayed as unsigned integer.
float %f data is displayed as floating point value without Exponent
%e or %E data is displayed as floating point value with exponent
char %c data is displayed as character
%s data is displayed as string
double %lf data is displayed as long float
long int %ld data is displayed as long integer.

m
2.2.2 Formatted input Function: scanf () function
 The function scanf (scan+ f) means scan the data in the buffer and format the data.

co
 Scan and Format: if data is in buffer, it is converted into appropriate data type using format string
with the help of conversion codes.
 scanf() function is used to read the data from the keyboard.
Syntax:
scanf (―format string‖, address list);
e.
Ex : scanf (―%d%f%c‖,&x,&y,&z);

format specifiers address list


dg

 A format specifiers starts with % sign and is followed by conversion code (i.e., d, f, c, s)
 Address list is a list of variables, each variable name must be preceded by an (&) ampersand symbol.
 The numbers of variables must be equal to the number of format specifiers.
 ‗&‘ is an ‗Address of‘ operator. It gives the location number used by the variable in memory.
ue

**Guidelines/Rules for scanf()


 Syntax:
scanf (―format string‖, address list);

 Always a format string should be enclosed within double quotes.


 No words, punctuation symbols, escape sequence characters (such as \t, \n etc) are allowed, only format
vt

specifiers are used in format string.


 A format specifiers starts with % sign and is followed by conversion code (i.e., d, f, c, s)
 There must be format specifier for each variable. i.e., number of format specifiers must be equal to the
number of variables.
Ex1: 1 + 1 + 1 = 3 format specifiers
//valid
scanf(― %d %f %c‖, &x, &y, &z);

1 + 1 + 1 = 3 variables

Ex2: 1 + 1 + 1 = 3 format specifiers


//invalid
scanf(― %d %f %c‖, &x, &y);

1 + 1 = 2 variables
 The variables present in scanf must represent the address of memory locations.
Ex1: int a;
scanf(―%d‖,&a); //valid
 The type conversion specified in each format specifier must match with the corresponding type of variable
present.
Ex1: int a;
scanf(―%d‖,&a);
//valid
integer integer value
Ex2: int a;
scanf(―%f‖,&a);

m
//invalid
float integer value

co
Format specifiers used in scanf()
Data type Format specifier Description
int %d Converts the data into decimal signed integer
%o Converts the data into octal integer
%x or %X Converts the data into hexadecimal integer
e. %u Converts the data into unsigned integer.
float %f Converts the data into floating point value without Exponent
%e or %E Converts the data into floating point value with exponent
char %c Converts the data into character
dg
%s Converts the data into string
double %lf Converts the data into long float
long int %ld Converts the data into long integer.

Example Programs:
1. Write a C program to calculate the sum of two numbers.
ue

#include <stdio.h>
void main() Enter the values for a, b:
{ 10 20
int a,b,sum; Sum = 30
printf (―Enter the values for a,b:\n‖);
scanf (―%d%d‖,&a,&b);
vt

sum = a+b ;
printf (―sum=%d‖ ,sum);
}
vt
ue
dg
e.
co
m

You might also like