Sie sind auf Seite 1von 36

Computer Programming

UNIT I
1.1 What is a computer?
A computer is an electronic device that manipulates information, or data. It has the ability to store,
retrieve, and process data.

1.2 Characteristics of Computer


1. SPEED : Computer is very fast calculating device. It can execute basic operations like subtraction,
addition, multiplication and division at a few microseconds. It can move and copy data at a speed in
the order of billion instruction per second.

2. ACCURACY : Computer always gives accurate results. The accuracy of Computer does not go
down when they are used continuously for hours together.
It always gives accurate results.

3. STORAGE CAPACITY : Computer have a very large storage capacity. A large volume of
information can be stored in the memory of computer and information can be retrieved correctly
when desired.

4. VERSATILITY : The working of computer with different types of data is known as versatility.
That means computer can perform different types of job efficiently. Computer can works with
different type of data and information such as visuals, text, graphics & vidio etc. So, versatility is a
most important characteristic of computer.

5. DILLIGENCE : A Computer can work for long hours with the same accuracy and speed because it
is free from problems of boredom or lack of concentration.

6. NO THOUGHTS : Computers have no thoughts because they are machine and they are devoid of
emotions. They have no feelings. Since, computers have no thoughts and feelings so they can't make
judgment based on thoughts and feelings.

1.3 Applications of computer


(i) Business
A computer has high speed of calculation, diligence, accuracy, reliability, or versatility which made it
an integrated part in all business organizations. Computer is used in business organizations for:
 Payroll calculations
 Budgeting
 Sales analysis
 Financial forecasting

1
 Managing employees database
 Maintenance of stocks etc.

(ii) Banking
Today banking is almost totally dependent on computer.
Banks provide following facilities:
 Banks provide online accounting facility, which includes current balances, deposits,
overdrafts, interest charges, shares, and trustee records.
 ATM machines are making it even easier for customers to deal with banks.

(iii) Insurance
Insurance companies are keeping all records up-to-date with the help of computers. The insurance
companies, finance houses and stock broking firms are widely using computers for their concerns.
Insurance companies are maintaining a database of all clients with information showing
 procedure to continue with policies
 starting date of the policies
 next due installment of a policy
 maturity date
 interests due
 survival benefits
 bonus

(iv) Education
The computer has provided a lot of facilities in the education system.
 The computer provides a tool in the education system known as CBE (Computer Based
Education).
 CBE involves control, delivery, and evaluation of learning.
 The computer education is rapidly increasing the graph of number of computer students.
 There are number of methods in which educational institutions can use computer to educate
the students.
 It is used to prepare a database about performance of a student and analysis is carried out on
this basis.

(v) Marketing
In marketing, uses of computer are following:
 Advertising - With computers, advertising professionals create art and graphics, write and
revise copy, and print and disseminate ads with the goal of selling more products.
 At Home Shopping - Home shopping has been made possible through use of computerised
catalogues that provide access to product information and permit direct entry of orders to be
filled by the customers.
2
(vi) Health Care
Computers have become important part in hospitals, labs, and dispensaries. The computers are being
used in hospitals to keep the record of patients and medicines. It is also used in scanning and
diagnosing different diseases. ECG, EEG, Ultrasounds and CT Scans etc., are also done by
computerised machines. Some major fields of health care in which computers are used are:
 Diagnostic System - Computers are used to collect data and identify cause of illness.
 Lab-diagnostic System - All tests can be done and reports are prepared by computer.
 Patient Monitoring System - These are used to check patient's signs for abnormality such as
in Cardiac Arrest, ECG etc.
 Pharma Information System - Computer checks Drug-Labels, Expiry dates, harmful drug’s
side effects etc.
 Surgery : Nowadays, computers are also used in performing surgery.

(vii) Engineering Design


Computers are widely used in Engineering purpose.
One of major areas is CAD (Computer aided design). That provides creation and modification of
images. Some fields are:
 Structural Engineering - Requires stress and strain analysis for design of Ships, Buildings,
Budgets, Airplanes etc.
 Industrial Engineering - Computers deal with design, implementation and improvement of
integrated systems of people, materials and equipments.
 Architectural Engineering - Computers help in planning towns, designing buildings,
determining a range of buildings on a site using both 2D and 3D drawings.

(viii) Military
Computers are largely used in defense. Modern tanks, missiles, weapons etc. Military also employs
computerized control systems. Some military areas where a computer has been used are:
 Missile Control
 Military Communication
 Military Operation and Planning
 Smart Weapons

(ix) Communication
Communication means to convey a message, an idea, a picture or speech that is received and
understood clearly and correctly by the person for whom it is meant for. Some main areas in this
category are:
 E-mail
 Chatting
 Usenet
 FTP
3
 Telnet
 Video-conferencing

(x) Government
Computers play an important role in government. Some major fields in this category are:
 Budgets
 Sales tax department
 Income tax department
 Male/Female ratio
 Computerization of voters lists
 Computerization of driving licensing system
 Computerization of PAN card
 Weather forecasting

1.4 Generation of Computers


The history of computer development is often in reference to the different generations of computing
devices. Each of the five generations of computers is characterized by a major technological
development that fundamentally changed the way computers operate. Most developments resulted
in increasingly smaller, cheaper, more powerful and more efficient computing devices.

Five Generations of Computers


First Generation: Vacuum Tubes
Second Generation Transistors
Third Generation Integrated Circuits
Fourth Generation Microprocessors
Fifth Generation Artificial Intelligence

(i) First Generation (1940-1956) Vacuum Tubes


The period of first generation was 1946-1959. The computers of first generation used vacuum tubes
as the basic components for memory and circuitry for CPU (Central Processing Unit). These tubes,
like electric bulbs, produced a lot of heat and were prone to frequent fusing of the installations,
therefore, were very expensive and could be afforded only by very large organizations. In this
generation mainly batch processing operating system were used. Punched cards, paper tape, and
magnetic tape were used as input and output devices. The computers in this generation used
machine code as programming language.

Advantages
 Vacuum tubes were the only electronic component available during those days.
 Vacuum tube technology made possible to make electronic digital computers.

4
 These computers could calculate data in millisecond.

Disadvantages
 The computers were very large in size.
 They consumed a large amount of energy.
 They heated very soon due to thousands of vacuum tubes.
 They were not very reliable.
 Air conditioning was required.
 Constant maintenance was required.
 Non-portable.
 Costly commercial production.
 Limited commercial use.
 Very slow speed.
 Limited programming capabilities.
 Used machine language only.
 Used magnetic drums which provide very less data storage.
 Used punch cards for input.
 Not versatile and very faulty.

Some computers of this generation were:


 ENIAC EDVAC UNIVAC IBM-701 IBM-650

(ii) Second Generation (1956-1963) Transistors


The period of second generation was 1959-1965. In this generation transistors were used that were
cheaper, consumed less power, more compact in size, more reliable and faster than the first
generation machines made of vacuum tubes. In this generation, magnetic cores were used as primary
memory and magnetic tape and magnetic disks as secondary storage devices. In this generation
assembly language and high-level programming languages like FORTRAN, COBOL were used. The
computers used batch processing and multiprogramming operating system.

Advantages
 Smaller in size as compared to the first generation computers.
 The 2nd generation Computers were more reliable
 Used less energy and were not heated.
 Wider commercial use
 Better portability as compared to the first generation computers.
 Better speed and could calculate data in microseconds
 Used faster peripherals like tape drives, magnetic disks, printer etc.
 Used Assembly language instead of Machine language.
 Accuracy improved.
5
Disadvantages
 Cooling system was required
 Constant maintenance was required
 Commercial production was difficult
 Only used for specific purposes
 Costly and not versatile
 Punch cards were used for input.

Some computers of this generation were:


 IBM 1620 IBM 7094 CDC 1604 CDC 3600 UNIVAC 1108

(iii) Third Generation (1964-1971) Integrated Circuits


The period of third generation was 1965-1971. The computers of third generation used integrated
circuits (IC's) in place of transistors. A single IC has many transistors, resistors and capacitors along
with the associated circuitry. The IC was invented by Jack Kilby. This development made computers
smaller in size, reliable and efficient. In this generation remote processing, time-sharing, multi-
programming operating system were used. High-level languages (FORTRAN-II TO IV, COBOL,
PASCAL PL/1, BASIC, ALGOL-68 etc.) were used during this generation.

Advantages
 Smaller in size as compared to previous generations.
 More reliable.
 Used less energy
 Produced less heat as compared to the previous two generations of computers.
 Better speed and could calculate data in nanoseconds.
 Used fan for heat discharge to prevent damage.
 Maintenance cost was low because hardware failure is reare.
 Totally general purpose
 Could be used for high-level languages.
 Good storage
 Versatile to an extent
 Less expensive
 Better accuracy
 Commercial production increased.
 Used mouse and keyboard for input.

Disadvantages
 Air conditioning was required.
 Highly sophisticated technology required for the manufacturing of IC chips.

6
Some computers of this generation were:
 IBM-360 series Honeywell-6000 series
 PDP(Personal Data Processor) IBM-370/168
 TDC-316

(iv) Fourth Generation (1971-Present) Microprocessors


The period of fourth generation was 1971-1980. The computers of fourth generation used Very Large
Scale Integrated (VLSI) circuits. VLSI circuits having about 5000 transistors and other circuit
elements and their associated circuits on a single chip made it possible to have microcomputers of
fourth generation. Fourth generation computers became more powerful, compact, reliable, and
affordable. As a result, it gave rise to personal computer (PC) revolution. In this generation time
sharing, real time, networks, distributed operating system were used. All the high-level languages
like C, C++, DBASE etc., were used in this generation.

Advantages
 More powerful and reliable than previous generations.
 Small in size
 Fast processing power with less power consumption
 Fan for heat discharging and thus to keep cold.
 No air conditioning required.
 Totally general purpose
 Commercial production
 Less need of repair.
 Cheapest among all generations
 All types of High level languages can be used in this type of computers

Disadvantages
 The latest technology is required for manufacturing of Microprocessors.

Some computers of this generation were:


 DEC 10 STAR 1000 PDP 11
 CRAY-1(Super Computer) CRAY-X-MP(Super Computer)

(v) Fifth Generation (Present and Beyond) Artificial Intelligence


The period of fifth generation is 1980-till date. In the fifth generation, the VLSI technology became
ULSI (Ultra Large Scale Integration) technology, resulting in the production of microprocessor chips
having ten million electronic components. This generation is based on parallel processing hardware
and AI (Artificial Intelligence) software. AI is an emerging branch in computer science, which
interprets means and method of making computers think like human beings. All the high-level
languages like C and C++, Java, .Net etc., are used in this generation.
7
AI includes:
 Robotics
 Neural Networks
 Game Playing
 Development of expert systems to make decisions in real life situations.
 Natural language understanding and generation.

The main features of fifth generation are:


 ULSI technology
 Development of true artificial intelligence
 Development of Natural language processing
 Advancement in Parallel Processing
 Advancement in Superconductor technology
 More user friendly interfaces with multimedia features
 Availability of very powerful and compact computers at cheaper rates

Some computer types of this generation are:


 Desktop Laptop NoteBook UltraBook ChromeBook

1.5 Classification of Computer


Computers may be classified based on the following: -
 Operating principles (based on their construction and working)
 Applications
 Size and capability (or classification into micro, mini, mainframe and supercomputers)
 Number of Microprocessors
 Word length and
 Number of users

8
1. Micro Computer or Personal Computer
 A PC can be defined as a small, relatively inexpensive computer designed for an individual
user.
 PCs are based on the microprocessor technology that enables manufacturers to put an entire
CPU on one chip.
 Businesses use personal computers for word processing, accounting, desktop publishing, and
for running spreadsheet and database management applications.
 At home, the most popular use for personal computers is playing games and surfing Internet.
 Although personal computers are designed as single-user systems, these systems are
normally linked together to form a network. In terms of power, now-a-days High-end models
of the Macintosh and PC offer the same computing power and graphics capability as low-end
workstations by Sun Microsystems, Hewlett-Packard, and Dell.

(i) Desktop computer :


 A desktop computer is a personal computer in a form intended for regular use at a single
location desk/table due to its size and power requirements, as opposed to a laptop whose
rechargeable battery and compact dimensions allow it to be regularly carried and used in
different locations.
 The most common configuration is a computer monitor, keyboard and mouse, and a case that
houses the main components of the PC, namely the power supply, motherboard, hard drive,
optical drive, and previously the floppy drive.
 The form factor of the case is typically an upright tower or (horizontal) desktop.
 All-in-one computers, that integrate the monitor and main PC components in one unit, are
often categorized under the desktop computer umbrella, particularly if they require an
external power source and separate keyboard/mouse.
 The desktop category has also encompassed home computers and workstations.

(ii) Laptop Computer:


 A laptop combines the components and inputs of a desktop computer, including display,
speakers, keyboard and pointing device (such as a touchpad or a trackpad) into a single
device.
 Most modern-day laptops also have an integrated webcam and a microphone.
 A laptop can be powered either from a rechargeable battery, or by mains electricity via an AC
adapter.
 Laptop is a diverse category of devices and other more specific terms, such as rugged
notebook or convertible, refer to specialist types of laptops, which have been optimized for
specific uses. Hardware specifications change significantly between different types, makes and
models of laptops.

9
(iii) Palmtop Computer/Digital Diary /Notebook /PDAs:
 A small computer that literally fits in your palm. Compared to full-size computers, palmtops
are severely limited, but they are practical for certain functions such as phone books and
calendars.
 Palmtops that use a pen rather than a keyboard for input are often called hand-held computers
or PDAs. Because of their small size, most palmtop computers do not include disk drives.
However, many contain PCMCIA slots in which you can insert disk drives, modems, memory,
and other devices.
 Palmtops are also called PDAs, hand-held computers and pocket computers.

2. Mini Computer
 A midsized computer. In size and power, minicomputers lie between workstations and
mainframes.
 In the past decade, the distinction between large minicomputers and small mainframes has
blurred, however, as has the distinction between small minicomputers and workstations.
 A minicomputer is a multiprocessing system capable of supporting from 4 to about 200 users
simultaneously.

3. Mainframe Computer
 A very large and expensive computer capable of supporting hundreds, or even thousands, of
users simultaneously.
 In the hierarchy that starts with a simple microprocessor (in watches, for example) at the
bottom and moves to supercomputers at the top, mainframes are just below supercomputers.
 In some ways, mainframes are more powerful than supercomputers because they support
more simultaneous programs.
 But supercomputers can execute a single program faster than a mainframe.

4. Supercomputer
 A supercomputer is a computer with great speed and memory.
 Supercomputers are very expensive and are employed for specialized applications that
require immense amounts of mathematical calculations.
 This kind of computer can do jobs faster than any other computer of its generation.
 They are usually thousands of times faster than ordinary personal computers made at that
time.
 Supercomputers can do arithmetic jobs very fast, so they are used for weather forecasting,
code-breaking, genetic analysis and other jobs that need many calculations.
 When new computers of all classes become more powerful, new ordinary computers are
made with powers that only supercomputers had in the past, while new supercomputers
continue to outclass them.

10
 The chief difference between a supercomputer and a mainframe is that a supercomputer
channels all its power into executing a few programs as fast as possible, whereas a mainframe
uses its power to execute many programs concurrently.

1.6 Organization of Computer


All types of computers follow a same basic logical structure and perform various operations for
converting raw input data into information useful to their users.

Hardware
Hardware represents the physical and tangible components of a computer i.e. the components that
can be seen and touched. Examples of Hardware are following:
 Input devices -- keyboard, mouse etc.
 Output devices -- printer, monitor etc.
 Secondary storage devices -- Hard disk, CD, DVD etc.
 Internal components -- CPU, motherboard, RAM etc.

Software
Software is a set of programs, which is designed to perform a well-defined function. A program is a
sequence of instructions written to solve a particular problem. There are two types of software
 System Software
 Application Software

Input Unit
This unit contains devices with the help of which we enter data into computer. This unit makes link
between user and computer. The input devices translate the information into the form
understandable by computer. Following are few of the important input devices which are used in a
computer:
11
 Keyboard Mouse Joy Stick
 Light pen Track Ball Scanner
 Graphic Tablet Microphone
 Magnetic Ink Card Reader(MICR) Optical Character Reader(OCR)
 Bar Code Reader Optical Mark Reader(OMR)

CPU (Central Processing Unit)


CPU is considered as the brain of the computer. CPU performs all types of data processing operations.
It stores data, intermediate results and instructions (program). It controls the operation of all parts
of computer.
CPU itself has following three components
 ALU(Arithmetic Logic Unit)
 Memory Unit
 Control Unit
CPU consists of the following features:
 CPU is considered as the brain of the computer.
 CPU performs all types of data processing operations.
 It stores data, intermediate results and instructions(program).
 It controls the operation of all parts of computer.

Memory or Storage Unit


This unit can store instructions, data and intermediate results. This unit supplies information to the
other units of the computer when needed. It is also known as internal storage unit or main memory
or primary storage or Random access memory (RAM). Its size affects speed, power and capability.
Primary memory and secondary memory are two types of memories in the computer. Functions of
memory unit are:
 It stores all the data and the instructions required for processing.
 It stores intermediate results of processing.
 It stores final results of processing before these results are released to an output device.
 All inputs and outputs are transmitted through main memory.

(i) Primary Memory (Main Memory)


Primary memory holds only those data and instructions on which computer is currently working. It
has limited capacity and data is lost when power is switched off. It is generally made up of
semiconductor device. These memories are not as fast as registers. The data and instruction required
to be processed reside in main memory. It is divided into two subcategories RAM and ROM.

Characteristics of Main Memory


 These are semiconductor memories
 It is known as main memory.
12
 Usually volatile memory.
 Data is lost in case power is switched off.
 It is working memory of the computer.
 Faster than secondary memories.
 A computer cannot run without primary memory.

(ii) Secondary Memory


This type of memory is also known as external memory or non-volatile. It is slower than main
memory. These are used for storing data/Information permanently. CPU directly does not access
these memories instead they are accessed via input-output routines. Contents of secondary
memories are first transferred to main memory, and then CPU can access it. For example : disk, CD-
ROM, DVD etc.

Characteristic of Secondary Memory


 These are magnetic and optical memories
 It is known as backup memory.
 It is non-volatile memory.
 Data is permanently stored even if power is switched off.
 It is used for storage of data in a computer.
 Computer may run without secondary memory.
 Slower than primary memories.

RAM (Random Access Memory)


 RAM(Random Access Memory) is the internal memory of the CPU for storing data, program
and program result. It is read/write memory which stores data until the machine is working.
As soon as the machine is switched off, data is erased.
 Access time in RAM is independent of the address that is, each storage location inside the
memory is as easy to reach as other locations and takes the same amount of time.
 Data in the RAM can be accessed randomly but it is very expensive.
 RAM is volatile, i.e. data stored in it is lost when we switch off the computer or if there is a
power failure. Hence a backup uninterruptible power system(UPS) is often used with
computers.
 RAM is small, both in terms of its physical size and in the amount of data it can hold.
 RAM is of two types
 Static RAM (SRAM)
 Dynamic RAM (DRAM)

ROM(Read Only Memory)


 ROM stands for Read Only Memory.

13
 The memory from which we can only read but cannot write on it. This type of memory is non-
volatile.
 The information is stored permanently in such memories during manufacture.
 A ROM, stores such instructions that are required to start a computer. This operation is
referred to as bootstrap.
 ROM chips are not only used in the computer but also in other electronic items like washing
machine and microwave oven.

Control Unit
This unit controls the operations of all parts of computer but does not carry out any actual data
processing operations. Functions of this unit are:
 It is responsible for controlling the transfer of data and instructions among other units of a
computer.
 It manages and coordinates all the units of the computer.
 It obtains the instructions from the memory, interprets them, and directs the operation of the
computer.
 It communicates with Input/Output devices for transfer of data or results from storage.
 It does not process or store data.

ALU (Arithmetic Logic Unit)


This unit consists of two subsections namely
 Arithmetic section
 Logic Section
(i) Arithmetic Section:
Function of arithmetic section is to perform arithmetic operations like addition, subtraction,
multiplication and division. All complex operations are done by making repetitive use of above
operations.
(ii) Logic Section:
Function of logic section is to perform logic operations such as comparing, selecting, matching and
merging of data.

Output Unit
Output unit consists of devices with the help of which we get the information from computer. This
unit is a link between computer and users. Output devices translate the computer's output into the
form understandable by users. Following are few of the important output devices which are used in a
computer.
 Monitors
 Graphic Plotter
 Printer

14
1.7 Algorithm
An algorithm is a step-by-step procedure to solve a given problem. An algorithm is a representation
of a solution to a problem.

Example
1. Algorithm to find out number is odd or even
step 1 : start
step 2 : input number
step 3 : rem=number mod 2
step 4 : if rem=0 then
print "number even"
else
print "number odd"
endif
step 5 : stop

2. Algorithm to swap two numbers


Step 1: Start
Step 2: Input two numbers(val1 and val2)
Step 3: Assign "val1" to a temporary variable (temp)
Step 4: Assign "val2" to "val1"
Step 5: Assign "temp" to "val2"
Step 6: Display values in val1 & val2

1.8 Flowchart
A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the
steps as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic
representation illustrates a solution model to a given problem. Flowcharts are used in analyzing,
designing, documenting or managing a process or program in various fields.

Flowcharting Symbols
There are 6 basic symbols commonly used in flowcharting of assembly language programs: Terminal,
Process, input/output, Decision, Connector and Predefined Process. This is not a complete list of all
the possible flowcharting symbols, it is the ones used most often in the structure of Assembly
language programming.

15
General Rules for flowcharting
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The
exit point for all flow
chart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long
as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart.
Examples are:
• From one page to another page.
• From the bottom of the page to the top of the same page.
• An upward flow of more then 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.

16
Example of a flowchart (Finding Factorial of a number)

1.9 Pseudocode
Pseudocode is an informal high-level description of the operating principle of a computer program or
other algorithm. It uses the structural conventions of a programming language, but is intended for
human reading rather than machine reading.

Example
Pseudocode to swap two numbers
swap(a, b)
t <- a
a <- b
b <- t
return a, b

17
UNIT –II

C is often called a "Middle Level" programming language. This is not a reflection on its lack of
programming power but more a reflection on its capability to access the system's low level functions.
Most high-level languages (e.g. Fortran) provides everything the programmer might want to do
already built into the language. A low level language (e.g. assembler) provides nothing other than
access to the machines basic instruction set.

2.1 Characteristics of C
 Well suited for structured modular programming.
 Robust language with rich set of built-in functions and operators.
 Has minimal instruction set and programs written in are efficient and fast.
 Highly portable.
 Highly flexible.
 Allows access to the machine at bit level (Low level (Bitwise) programming).
 Supports pointer implementation -extensive use of pointers for arrays, structures, and
functions.

2.2 Structure of C Program


A C program basically has the following form:

Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{
Declaration Section
Executable part
}
Subprogram section
Function 1
Function 2
..
function n

The Documentation Section consists of a set of comment lines giving the name of the program and
other details.
The Link Section provides instructions to the compiler to link functions from the system library.
18
The Definition Section defines all symbolic constants.
The Global Declaration Section: There are some variables and those variables are declared in this
section that is outside of all functions.
main() function: Every C program must have one main function section. This section contains two
parts, declaration and executable part.
Declaration Part declares all the variables used in the executable part.
There should be at least one statement in the executable part which contains instructions to
perform certain task.
The declaration and executable part must appear between the opening and closing braces. All
statements in the declaration part should end with the semicolon.
The Subprogram Section contains all the user defined functions that are called in the main function.

Example Program
/*Documentation Section: program to find the area of circle*/
#include "stdio.h" /*link section*/
#include "conio.h" /*link section*/
#define PI 3.14 /*definition section*/
float area; /*global declaration section*/
void main()
{
float r; /*declaration part*/
printf("Enter the radius of the circle\n"); /*executable part starts here*/
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}
Note
 C is a case sensitive programming language. It means in C printf and Printf will have different
meanings.
 C has a free-form line structure. End of each C statement must be marked with a semicolon.
 Multiple statements can be one the same line.
 White Spaces (ie tab space and space bar ) are ignored.
 Statements can continue over multiple lines.

2.3 C Compilation Model


Figure shows the C compilation model that consists of preprocessor, compiler, assembler and link
editor. The function of those thinks which are described below:

19
(i) Preprocessor
 The Preprocessor accepts source code as input and interprets special preprocessor directives
denoted by #.
 It is also responsible for removing comments and empty programming lines.

(ii) Translator
A translator is a computer program that performs the translation of a program written in a given
programming language into a functionally equivalent program in a different computer language,
without losing the functional or logical structure of the original code.

Compiler
A compiler is a program that takes a input program on one programming language (source language)
and produces output in another language (object language or target language).

Interpreter
An interpreter is another common kind of language processor. Instead of producing a target program
as a translation, an interpreter appears to directly execute the operations specified in the source
program on inputs supplied by the user.
20
Assembler
Assembler which converts assembly language programs into object files. Object files contain a
combination of machine instructions, data, and information needed to place instructions properly in
memory.

(iii) Link Editor


 If a source file has references, library functions or functions defined in other source files, then
the link editor combines these functions with main() to create an executable file.
External variable references are also resolved here.

2.4 Features of C
o Low level language support
o Program portability
o Powerful and Feature Rich
o Bit Manipulation
o High Level Features
o Modular Programming
o Efficient use of Pointers

2.5 Character Set


A character set defines the valid characters that can be used in source programs or
interpreted when a program is running. The only characters required by the C Programming
Language are as follows:
 Letters
Uppercase A….Z
Lowercase a….z
 Digits
All dec imal digits 0…9
 Special characters

21
Symbol Meaning Symbol Meaning
~ Tilde - Minus sign
! Exclamation mark = Equal to sign
# Number sign { Left brace
$ Dollar sign } Right brace
% Percent sign [ Left bracket
^ Caret ] Right bracket
& Ampersand : Colon
* Asterisk " Quotation mark
( Lest parenthesis ; Semicolon
) Right parenthesis < Opening angle
bracket
_ Underscore > Closing angle bracket
+ Plus sign ? Question mark
| Vertical bar , Comma
\ Backslash . Period
` Apostrophe / Slash

 Escape Sequences

Escape Escape
Description Description
Sequence Sequence
\a Audible alert(bell) \v Vertical tab
\b Backspace \\ Backslash
Double quotation
\f Form feed \”
mark
\n New line \’ Single quotation mark
\r Carriage return \? Question mark
\t Horizontal tab \0 Null

22
2.6 Tokens
A token is a sequence of characters that is understood as a unit. Tokens are the basic building
blocks of a C program. C tokens fall roughly into the six categories listed below.
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1. Keywords
C keywords are the words that convey a special meaning to the c compiler. The keywords cannot be
used as variable names because by doing so, we are trying to assign a new meaning to the keyword
which is not allowed. The list of C keywords is given below:

auto break case char const


continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while

2. Identifiers
Each program elements in a C program are given a name called identifiers. Names given to
identify Variables, functions and arrays are examples for identifiers. eg. x is a name given to integer
variable in above program.

There are certain rules that should be followed while naming c identifiers:
 They must begin with a letter or underscore (_).
 They must consist of only letters, digits, or underscore. No other special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only first 31 characters are significant.

Examples of acceptable identifiers are:


TOTAL, Sum, Net_sal, P123, a_b_c, total, _sysreg

23
Examples of unacceptable identifiers are:
Bas ic (blank not allowed)
H, rent (special character `, ' included)
It may be noted here that TOTAL and total are two different identifier names.

3. Constants
C Constants refers to the data items that do not change their value during the program execution.
Several types of C constants are available in C.

Types of C constant

S.No Constant type data type Example


int 53 , 762 , -478 , etc
unsigned int 5000u , 1000U , etc
1 Integer constants
long int 1000L , -300L , etc
long long int 5555555LL
111.22F , 2.22e-2f
Real or Floating
2 float, doule 111.22 , 4.0 ,
point constants
-0.34565
24
3 Octal constant int 013 /* starts with 0 */
Hexadecimal
4 int 0×90 /* starts with 0x */
constant
5 character constants char ‘A’ , ‘B’, ‘C’
6 string constants char “ABCD” , “Hai”

Rules for constructing C constant


 Integer Constants
1. An integer constant must have at least one digit.
2. It must not have a decimal point.
3. It can either be positive or negative.
4. No commas or blanks are allowed within an integer constant.
5. If no sign precedes an integer constant, it is assumed to be positive.
6. The allowable range for integer constants is -32768 to 32767

 Real Constants
1. A real constant must have at least one digit
2. It must have a decimal point
3. It could be either positive or negative
4. If no sign precedes an integer constant, it is assumed to be positive.
5. No commas or blanks are allowed within a real constant.

 Character constants
1. A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas. Both the inverted commas should point to
left.
2. For example, ’C’ is a valid character constant whereas ‘C’ is not.
3. The maximum length of a character constant is 1 character

Backslash Character Constants


There are some characters which have special meaning in C language. They should be
preceded by back slash symbol to make use of special function of them. Given below is the list of
special characters and their purpose.

Character Meaning Character Meaning


\b Backspace \\ Backslash
\f Form feed \v Vertical tab
\n New line \a Alert or bell

25
Carriage
\r \? Question mark
return
Octal constant (N is an octal
\t Horizontal tab \N
constant)
Hexadecimal constant (N –
\” Double quote \XN
hex.dcml cnst)
\’ Single quote \\ Backslash

4. Strings
Strings are sequence of characters enclosed within double quotes. For example,
“hello”, “abc”, “hello911″
Every string constant is automatically terminated with a special character ‘\0′ called the null
character which represents the end of the string.
For example, “hello” will represent “hello\0″ in the memory.
Thus, the size of the string is the total number of characters plus one for the null character.

5. Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be used
for some other purpose.
[] () {} , ; : * … = #

Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and function parameters.
Brackets[]: Opening and closing brackets are used as array element reference. These indicate single
and multidimensional subscripts.

6. Operators
 The symbols which are used to perform logical and mathematical operations are called C
operators.
 These C operators join individual constants and variables to form expressions. Operators,
functions, constants and variables are combined together to form expressions.
Example : A + B * 5
where,
+, * - operators
A, B - variables
5 – constant
A + B * 5 - expression

26
2.7 Data Types
Data type is nothing but the type of data that can be stored in the variables. It plays a dynamic role in C
programs. Any variables that should be declared with the corresponding data type before using it. This data
type is used to define the size of memory that is needed for the variable. For example, if any variable that
should be declared as int, and then it occupies only two bytes of memory. Based on the data type declared
for the variables, the memory is going to be allocated. Suppose, if the value which are assigned to the
variable is mismatched, then it displays an error. In C, there are four major data types are used such as
basic data type, enumerated data type derived data type and void data type.

S.No Data Types Example


1 Basic data types int, char, float, double
2 Enumeration data type enum
3 Derived data type pointer, array, structure, union
4 void data type void

1. Basic data types


C supports four basic data types such as int, char, double and float. All these types are accepts different
types of values. All basic data types are explained below:

Integer Data Character Data Floating Point Type Double Data Type
Type Type
Keyword int char float double
The integer data This data type Floating point data type is one of the basic data
Definition type which which allows a types which allows too define floating point
allows the variable to store numbers or real numbers. It may be of 2 types.
variable to store only one One is float and another one double.
numeric values. character.
4 bytes (six 4 bytes (ten
Size 2 bytes 1 byte decimal fraction) decimal fraction)
-32,768 to 1E–37 to 1E+37 with 1E–37 to 1E+37
Range +32,767 –127 to 127 six digits of precision with ten digits of
precision

C – Modifiers
The modifier which allows the amount of memory space to be allocated for the given variable. Modifiers
are prefixed with basic data types to modify (either increase or decrease) the amount of storage space
allocated to a variable. For example, storage space for int data type is 4 byte for 32 bit processor. We can
increase the range by using long int which is 8 byte. We can decrease the range by using short int which is
2 byte. There are 5 modifiers available in C language.

27
They are,
1. short
2. long
3. signed
4. unsigned
5. long long
Table gives the detail about the storage size of each C basic data type in 16 bit processor.

Data Storage
Modifiers Range
Types Size
char char 1 –127 to 127
int 2 –32,767 to 32,767
long int 4 –2,147,483,647 to 2,147,483,647
short int 2 –32,767 to 32,767
unsigned short int 2 0 to 65,535
int signed short int 2 –32,767 to 32,767
long long int 8 –(2power(63) –1) to 2(power)63 –1
signed long int 4 –2,147,483,647 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
unsigned long long int 8 2(power)64 –1
float 4 1E–37 to 1E+37 with six digits of precision
float double 8 1E–37 to 1E+37 with ten digits of precision
long double 10 1E–37 to 1E+37 with ten digits of precision

2. Enumeration data type


Enumeration data type is a user defined data type that assigns values during compilation time. It
consists of integer constants that should be named as a list. It always starts with 0(zero) by default and
values are incremented by 1 for the next identifiers in the list. It can be specified using the keyword ‘enum’.

Syntax
enum identifier { enumerator-list }

Example
enum colour { green, red, blue, white }
The variables will be assigned by the values that start from 0. Green=0, red=1, blue=2 and white=3.
enum colour { green=1, red, blue, white}
The value 1 is assigned to green by default. The values for the next variables are incremented from the
default value 1. Now red=2, blue=3 and white=4.

28
3. Derived data type
The derived data type is not created; which is to be derived from the basic data types. The examples
are Array, pointer, structure and union. All these derived data types will be explained in the upcoming
chapters.

4. void data type


void is an empty data type that has no value. It can be used in functions and pointers. The keyword
void is used to define void data type. If any function does not return any value then we specify the return is
as void.

2.8 Operators
An operator is a symbol that specifies which operation to perform in a statement or expression. An
operand is one of the inputs of an operator. For example, in expression b+c, + is the operator and b
and c are the operands. Operators follow a strict precedence, which defines the evaluation order of
expressions containing these operators. Operators with the same precedence associate with either
the expression on their left or the expression on their right, depending on their associativity. C
language supports following type of operators.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and Decrement Operators
 Conditional Operators
 Bitwise Operators
 Special Operators

1. Arithmetic Operators
This operator which helps to perform the basic arithmetic or mathematic operations such as
addition, subtraction, multiplication, division and modulo operation. The arithmetic operators which
are used in the arithmetic expressions are ‘+’ (addition), ‘-‘(subtraction), ‘*’(multiplication), ‘/’
division and ‘%’ for modulo division.

To perform arithmetic operations, we need two operands. One is placed in the left side of the
operators and another one operand is placed in the right side of the operator. It is also called as the
binary operators, since it uses two operands for evaluation. After the evaluation is carried out, the
result will be stored in another variable which are placed in the left side of the expression.

Operator Meaning Examples


+ Addition 1+4 = 5

29
- Subtraction 4 -2 = 2
* Multiplication 2*5 = 10
/ Division 6/2 = 3
% Modulo division 10/3= 1

Sample Program
#include <stdio.h>
#include <conio.h>
int main()
{
int a=2,b=3,c;
c=a+b; //Arithmetic operation
printf("\n Addition of 2 numbers are %d", c);
return 0;
}

Output
Addition of 2 numbers are 5

2. Relational Operators
This relational operator is used to compare the values of two or more operands. Operands that may
be variables, constants or expression. This operator is also having two operands for processing. One
is placed in the left and another one is placed in the right side of the operator. There are six relational
operators are there and the result of these operators will be either 0(FALSE) or 1(TRUE).

Operator Meaning Example Return value


< is less than 2<6 1
<= is less than or equal to 3<=4 1
> is greater than 5>17 0
>= is greater than or equal to 47>=5 0
== equal to 6==6 1
!= not equal to 5!=5 0

This relational operators can be used in the ordinary statements or branching statements.

Sample Program

#include <stdio.h>
#include <conio.h>

30
int main()
{
int a=2,b=3,c;
c=a>b;
printf("\n Result is %d", c);
return 0;
}

Output
Result is 0

3. Logical Operators
This operator is used to combine the results of two or more relational expressions. There are three
logical operators are there: and, or, not. The operators are:

Operator Meaning Example Return value


&& Logical AND (5>2) && (16>4) 1
|| Logical OR (9>4) || (3<4) 1
! Logical NOT !4 0

The logical operators AND and OR which have the expressions on both side of the operator. For NOT
operator, the expression will be placed in the right side of the operator only. The result of the logical
operators will be either 0(FALSE) or 1(TRUE).

The logical AND operator returns TRUE if both the expressions are TRUE. Otherwise it returns
FALSE. The logical AND operator. The logical OR operator returns FALSE if both the expressions are
FALSE. Otherwise it returns TRUE. The logical NOT operator returns TREU if the expression is FALSE.
Otherwise it returns TRUE.

The truth tables for the logical operators are:

Logical OR Logical AND Logical NOT


Ex1 Ex2 Result Ex1 Ex2 Result Ex Resul
t
0 0 0 0 0 0
0 1 1 0 1 0 0 1
1 0 1 1 0 0
1 1 1 1 1 1 1 0

31
Sample Program

#include <stdio.h>
#include <conio.h>
int main()
{
int a=2,b=3,c=5,d,e,f,g;
d=a>b && b<c;
e=a>b || b<c;
f=!a>b;
g=(a>b)&&(b>c)||(a<c);
printf("\n Result of AND operator is %d", d);
printf("\n Result of OR operator is %d", e);
printf("\n Result of NOT operator is %d", f);
printf("\n Result of All operators is %d", g);
return 0;
}

Output
Result of AND operator is 0
Result of OR operator is 1
Result of NOT operator is 0
Result of All operators is 1

4. Assignment Operators
The assignment operator ‘=’ is used to assign the value of expression to the variable which is placed
in the left side. The expression may be a constant or variable or expression. The general syntax is:
Variable = Expression;
For example, a=5 // constant 5 is assigned to the variable a
a=c; // value of c is assigned to a
a= b+c*d; // The expression b+c*d is evaluated and store the result in a.

5. Increment and Decrement Operators


In C, ++ and -- are the increment and decrement operators respectively. Both of these operators are
unary operators, which means that it process with only one operand. Increment operator which adds
1 to the value of operand and decrement operator which subtracts 1 from the value of operand
respectively. For example, Let us have, a=5 and b=10
a++; //a becomes 6
b--; //b becomes 9

32
The increment operator which can be of two types: Pre increment operator and post increment
operator. In pre increment operator, the operator is placed before the operands. For example ++a
which increment the value of a by 1 and use its value later. In post increment operator, the operator
is placed after the operands. For example, a++ which use the value of a first and then increase its
value by 1.

The decrement operator which can be of two types: Pre decrement operator and post decrement
operator. In pre decrement operator, the operator is placed before the operands. For example --a
which decrement the value of a by 1 and use its value later. In post decrement operator, the operator
is placed after the operands. For example, a-- which use the value of a first and then decrease its
value by 1.

Sample Program

#include <stdio.h>
int main()
{
int c=2;
printf("%d\n",c++); //this statement displays c and then, incremented.
printf("%d",++c); //this statement increments c and then displayed.
printf("%d\n",c--); //this statement displays c and then, decremented.
printf("%d",--c); //this statement decrements c and then displayed.
return 0;
}

Output
2
4
4
2

6. Conditional Operators
Conditional operators or the ternary operators are used for decision making in C. The operator are
question mark (?) and the colon (: ). The general syntax is:
Variable = condition? exp1: exp2
The ‘?’ operator act as ternary operator, it first evaluate the condition, if it is true then exp1 is
evaluated or exp2 is evaluated. The result of either exp1 or exp2 is assigned to the left side variable.

33
Sample Program

#include <stdio.h>
int main()
{
int a=2,b=3,ans;
ans=a>b?a:b; //ternary operator
printf("%d",ans);
return 0;
}

Output
3

7. Bitwise Operators
A bitwise operation operates on one or more bit patterns or binary numerals at the level of their
individual bits. Bitwise operators are used in bit level programming. The bitwise operators are
shown in the table

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement

All the bitwise operators are the binary operators, since it takes two (binary) operands. The operator
is placed between left operand and the right operand. The truth table for the Bitwise AND, OR and
XOR operator is shown in table.

Bitwise AND Bitwise OR Bitwise XOR


(both the operand should (either of the operand (the two operands should
be high for 1) should be high for 1) be different for 1)
0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 0

34
Sample Program

#include <stdio.h>
int main()
{
int a=12,b=6;
printf(“\n Result of Bitwise AND is %d”,a&b);
printf(“\n Result of Bitwise OR is %d”,a|b);
printf(“\n Result of Bitwise XOR is %d”,a^b);
printf(“\n Result of Bitwise Left Shift is %d”,a<<b);
printf(“\n Result of Bitwise Right Shift is %d”,a>>b);
return 0;
}

Output
Result of Bitwise AND is 4
Result of Bitwise OR is 14
Result of Bitwise XOR is 10
Result of Bitwise Left Shift is 768
Result of Bitwise Right Shift is 0

8. Special Operators
Some special operators are also available in C. They are

(i) Comma Operator


Comma operators are used to link or group the related expressions together.
For example:
int a, c=5,d;

(ii) The sizeof operator


It is a unary operator used to find the size of data type such as primitive and derived data types.

Sample Program

#include <stdio.h>
void main()
{
int a; float b; double c; char d;
printf("Size of int=%d bytes\n",sizeof(a));

35
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
}

Output
Size of int=4 bytes
Size of float=4 bytes
Size of double=8 bytes
Size of char=1 byte

36

Das könnte Ihnen auch gefallen