Sunteți pe pagina 1din 75

GE6151-Computer Programming

Sem/Year: I/I Regulation: 2013


Unit-1
Generations of Computer:
 It means step by step growth in the technology.
 Each phase of computer has been extended to include both hardware and software, together make up
an entire computer system.
 Based on the period of development, the features and technological advancement, the computer has
been classified into various generations.
 There are five generations of computer:
1. First generation
2. Second generation
3. Third generation
4. Fourth generation
5. Fifth generation

T
1. First generation:
 The late forties and the early fifties have seen computer hardware using “vacuum tubes”.

E
 The concept of stored program was introduced by “von newmann”.
 Vacuum tube circuitry as such these were quite large.

.N
 Vacuum tube was one of the high speed electronic devices and could perform computations in
milliseconds.
 In this generation used the “machine language binary language.(0’s &1’s)
 No operating system used.
 MEMORY: 10000 to 20000 characters.
IA
ND
Advantages:
1) Vacuum tubes were the only electronic components.
2) The fastest calculating device.
3) It performs computations in milliseconds.
NI

4) It first digital computers.


Disadvantages:
1. very big in size
I

2. high heat production


.K

3. high power consumption


4. no reliability
5. need constant maintenance
W

2. Second generation:
 ”John Bardeen” invented a new electronic device called “transistor”.
 It is very small in size &less expensive &produces less heat.
W

 The storage capacity: up to 64000 characters.


 They used “Assembly level” programming language.
 Memory: magnetic core & magnetic disk.
W

 Batch operating systems ruled the second generation compute in micro seconds.
Advantages:
1) Small in size
2) Better reliability
3) Computational time is micro seconds
4) Less heat generated
5) Better speed & portability
Disadvantages:
1) Need air-conditioning
2) High cost
3) Frequent maintenance required
3. Third generation:
 These generations were introduced in the mid sixties.
 these were based on “Integrated circuits(IC)”
 The IC chips were made of silicon.
 MEMORY:”semi conductor memory”.
 Programming language “high level language” used
 Memory capacity: up to “4 million characters”.
 It performs computations in “nano seconds”.
 FORTRAN, BASIC, PASCAL, COBOL languages are used.
Advantages:
1) Small in size
2) More reliability
3) Less heat generated
4) Computational time in nano seconds.
5) Low maintenance cost
Disadvantages:
1. need air-conditioning
2. special technology for manufacture of IC chips
 Example: IBM, CDC, PDP, ICL, Honeywell.
4. Fourth generation:

T
 Development of the microprocessor in 1972.
 when integrated with storage, input & output units, a microprocessors produces a micro

E
computer
 They are interactive & respond directly * immediately to the user’s input.

.N
 the languages used: 4th generation language
 MEMORY: “semi conductor memory(no range)
 Processing speed: 1 to 10 nano seconds.
Advantages:
1) Small in size
IA
ND
2) Very cheap
3) Consumed less power
4) Having more reliability
5) Object oriented languages are supported
NI

Disadvantages:
1) Special technology required for manufacture of LSI chips.
 Example: INTEL, APPLE, IBM
I

5. Fifth generation:
.K

 Computers are machines that perform only when instructed.


 They may operate at fast speed & perform with unbelievable accuracy.
 But they are unable to act (or) think on their own.
W

 artificial intelligence machine could be developed which will be think & decide
 MEMORY: “magnetic bubble memories”(CMOS).
 Speed: 1 to 100 nano seconds.
W

Languages: artificial intelligence


Advantages:
W

1) More user friendly


2) Support parallel programming & user friendly environment.
3) This generation is super computers.
4) It supports power applications.
Characteristics of computer:
o The computer is an intelligent machine that solves problems and performed much faster,
accurately and efficiently.
o The characteristics of computers are listed below:
1. Speed
2. Accuracy
3. Automatic
4. Endurance
5. Versatility
6. Storage
7. Reduction in cost
8. No intelligent quotient
1. Speed:
o Speed is the most important characteristic of a computer.
o It can perform in few seconds, the amount of work that a human being can do in an entire
year.
Example:
10 digit numbers multiply with 5 digit number human take hours and hours. But computer
take only few nano seconds.
2. Accuracy:
o The computers are perfect, accurate and precise(correct)
o Accuracy signifies (mention) the reliability of the hardware components of a computer.
Example:
Only an accurate computer can guide a rocket to reach the space in the pre determined path.
3. Automatic:
o The computers are works automatically.
o Once programs are stored & data given to it, then every instruction automatically transferred one
by one for execution.
o The CPU follows these instructions until it meets the last instruction execution.

T
4. Endurance:
o The computer can go on working continuously and does not suffer tiredness and lack of

E
concentration.
Example:

.N
If three million calculations given to computer, three millionth calculate give the same
accuracy and same speed of first calculation.
5. Versatility:
IA
o The computer can be put to various jobs and has applications in various fields.
Example: Weather forecasting, teaching, railways, medicine, industry and banking, etc.,
6. Storage:
ND
o The computer processes limitless quantities of data and information.
o Various memories such as primary, secondary.
Example: Random Access Memory (RAM), Hard Disk Drive (HDD), Floppy, Magnetic tapes.
7. Reduction in cost:
NI

o Initial investment cost may be high, but reduces the cost of each transaction and cost of
computers.
o It reduces man power and space requirements and greater efficiency.
I

8. No intelligent quotient:
.K

o The computer carryout task much faster than human being.


o But computer cannot think its own.
Classification of computers:
W

 Computes are available in different shape, size &weights.


 The computers are classified as following:
W

Based on Hardware Design Analog


Digital
Hybrid
W

Based on Utility General Purpose Computer


Special Purpose Computer
Based on Size & Capacity Micro Computers
Mini Computers
Main Frame Computers
Super Computer
Based on Mode of use Palmtop
laptop
Personal Computer
Work Station
Main Frame System
Clients & Server

BASED ON HARDWARE DESIGN:


 Based on Hardware Design Computers are classified as
(a)Analog Computer
(b)Digital Computer
(c)Hybrid Computer
(a)Analog Computer
 The Analog computer operate by “Measuring” instead of “Counting”
 Computers are carried out with physical qualities such as voltage, length, current, Temperature.
 Analog Computer, the input data is Continuously Changing electrical (or) non-electrical
information.
Example: Electronic weighing scale, patient heart beat, blood pressure, temperature.
(b)Digital Computer
 Digital computer with quintiles represented as digits
 It both numeric & non-numeric information is representation as strings of digits.
 It represented by binary numbers 0’s &1’s.
 A digital signal consists of discrete voltage level represent binary 1 (ON) (or) binary 0(OFF)
 It is much faster than Analog Computers
Example: Business, Scientific Applications

T
(c)Hybrid Computer
 Hybrid Computers, made combine the qualities of both analog & Digital Computers.

E
 Measuring functions are performed by the analog way.
 Logic functions are designed in nature

.N
Example: Personal Computer
Analog Digital
1)It operates by measuring
2)the calculations are converted to equation &
converted into electrical signals
IA
1)It operates by Counting
2)the calculations are converted into Binary
values(0’s&1’s)
ND
3)Less accurate 3)More accurate
4)lass Speed 4)High Speed
5)Limited Memory 5)More Memory
6)Lack of Flexible 6)Highly Flexible
7)Limited Applications 7)Many number of Applications
NI

BASED ON UTILITY:
I

Based on utility the computers can be classified into


.K

(a)General Purpose Computer


(b)Special Purpose Computer
(a)General Purpose Computer
W

 These are designed & constructed to satisfy almost all the need of the society.
 They are able to perform according to the program created to meet different needs.
 These can used for Varity of tasks financial accounting, Designing textile prints and etc.
W

 They are also flexible & can be used to work on business & scientific problems.
(b)Special Purpose Computer
 Special Purpose Computer can be designed to perform specific functions.
W

 In such devices, the instructions are permanently pre programmed in internal memory.
 Some of Special Purpose Computers are aircraft control system, electronic voting machines &
Computer in hospital, etc.
BASED ON SIZE & CAPACITY:
 Based on size & capacity, Computers are classified into the following:
(a) Micro Computer
(b) Mini Computer
(c) Main frame Computer
(d) Super Computer
(a)Micro Computer
 Micro computers are small in size use of microprocessor
 A microprocessor is a processor whose components of input, output & CPU are in single IC chip
 These are used in office, homes, schools, shops, stores, .etc.
(b) Mini Computer
 Mini computers larger than micro computers &more powerful in terms of processing speed
 It mainly multiprocessor systems where many operations can perform simultaneously.
 It has greater storage capacity & larger memories as compared to micro computer
 These are handling more Input & Output devices.
c) Mainframe computer:
 Mainframe computer are larger, faster &more expensive than other computers.
 These are used to handle huge volumes of data.
 These computers work with more than one processor at same time.
 These are multiuser, multi processor system.
 These are used to solve the very complex calculations.
 It is used in large industries, government organizations, banks, airline reservations. Where large
database is required.

d) Super computer:
 Super computer is the most powerful of all computers.
 They are high speed.
 They are mainly used for purposes handle very large amount of data & to be processed within a
very short time.

T
 It is used in weather forecasting, space research, weapons research, atomic research, design of
aircrafts, etc….

E
BASED ON MODE OF USE:

.N
Based on made of use can be classified into
A. Palmtop,
B. Laptop,
C. Personal computer,
D. Work station,
E. Clients & server.
IA
ND
a) Palmtop:
 Palmtop is accepting hand written inputs using an electronic pen.
 These have small disk storage &connected to a wireless network.
 A palmtop computer has also facilities to be used as phone &tablets.
NI

b) Laptop computer:
 Laptops are portable computer with less weight & small in size to rest on the lap.
 Laptops are attached with keyboard, mouse, monitor & CPU in single booklet.
 It will run in batteries & connected to a network.
I
.K

 It used for miniature components which consume low power.


c) Personal computer:
 The personal computer is name itself implies the use of personal things.
W

 It mainly designed to meet personal computing requirements of users at working place (or) at home.
 It is non-portable & general purpose computer. This can easily fit in on office table.
 It is rapidly changed the work culture &individuals.
W

 The pc used by children & all the peoples & everywhere.


 It is usually designed two models:
i) Desktop model--------- bed type CPU
W

ii) Tower model-------------stand type CPU.


d) Workstation:
 It is a powerful desktop computer designed to meet computing needs of users or clients.
 It has better processing, high storage &effective graphics display.
 It is similar to pc can be used through “local area network” (LAN).
e) Clients & server:
 With the increased gain of computer networks, it is possible to interconnect several computers.
 It is very useful to share resources & services among the multiple users.
 There are two varieties of system used.
Server:
 It is a large computer that manages a shared resources &services to the clients.
Clients:
 It is single pc & supports a user friendly interface with end user.
 It sends the request to the server &accesses the resources in server.

BASIC ORGANIZATION OF COMPUTER

M
 The architecture of the computer has not changed, but the technology may be vary from one computer
to another computer.
 However, the basic organization of computers remains the same for all computers.
 The basic computer architecture shown in the figure.

The computers have the following three units:


1. Input unit
2. Central processing unit
3. Output unit

Central Processing Unit (CPU)

T
Control Unit

E
.N
Input Unit Memory Unit Output Unit

Control Flow
Arithmetic and
Logic Unit
IA
ND
Data Flow

Secondary storage
NI

1. INPUT UNIT:
o Computer must need the data and instructions in order to solve any problem.
I

o Therefore we need to give data and instruction through the input unit.
.K

o The input unit consists of one or more input devices.


Input Device Functions:
i. Accept data and instruction from the outside word.
W

ii. Convert it to a form that the computer can understand.


iii. Supply the converted data to the computer.
W

Following are some of the input devices:


Keyboard, mouse, light pen, joystick, Optical Character Recognizer (OCR), Optical Mark Recognizer
(OMR), Track ball, etc.,
W

2. CENTRAL PROCESSING UNIT:


o It is the heart and brain of the computer.
o Because of all operations are carried out in CPU only.
o CPU doing the following operations :
(i) All calculations and all decisions.
(ii) Controls and co-ordinates all units
(iii) Interprets (converts) instructions of program.
(iv) Stores data temporarily and monitors the external request.
CPU is sub divided into following:
(i) Control unit
(ii) Arithmetic & logic unit
(iii) Memory unit
a) Primary storage
b) Secondary storage
i) Control unit:
o The control unit instructs the computer how to carry out program instruction.
o It drives the flow of data between memory and arithmetic and logic unit
o It controls and co-ordinates the all other units.
o The input unit does not know when receive data & where to put the data.
o It drives & instruct the receiving it.
o It controls the flow of data & instruction from & to of
(i) Storage, ALU
(ii) ALU, storage.
o The control unit also controls what should be sent to the output unit.
o During program execution, control unit fetches instruction from primary memory, decodes them
to determine which operation required.
ii) Arithmetic & logic unit:
 Arithmetic& logic unit performs all the arithmetic &logical operations.
 Arithmetic operations like additions, subtractions, multiplications, divisions.
 Logical operations like AND, OR, NOT for comparisons.
 ALU also does comparisons &takes decision; the control unit transfers the required data from storage
unit to ALU.
 Calculations finished data transferred to storage unit.

T
iii) Memory unit:
o Memory is the part of computer holds data for processing.

E
o Memory is divided into two categories:
a) Primary memory

.N
b) Secondary memory
o A memory that stores program instructions (or) data used by CPU for performing any operations.
o Memory is device which store information temporarily (or) permanently.
a) Primary memory: IA
o The primary memory also called as “main memory”.
o It hold the program being currently executed in the computer,
ND
o This primary memory is temporarily store the data for processing by CPU.
o The RAM (Random Access Memory) used as primary memory.
o Each &ever information can process through any main memory.
o It is fast & expensive.
NI

o Computer speed also include with this memory.


RAM ROM
Random Access Memory or RAM is a form of data Read-only memory or ROM is also a form of data
I
.K

storage that can be accessed randomly at any time, in storage that cannot be easily altered or
any order and from any physical location. Allowing reprogrammed.
quick access and manipulation.
W

Random Access Memory Read-only memory


RAM allows the computer to read data quickly to run ROM stores the program required to initially boot
applications. It allows reading and writing. the computer. It only allows reading.
W

RAM is volatile i.e. its contents are lost when the It is non-volatile i.e. its contents are retained even
device is powered off. when the device is powered off.
The two main types of RAM are static RAM and The types of ROM include PROM, EPROM and
W

dynamic RAM. EEPROM.

b) Secondary storage:
 The secondary storage is also known as auxiliary storage.
 It is used like an archive (secure) & permanent storage.
 It may store several programs, documents, database, etc.
 After running the program, we need to save the results and program, transfer them to secondary
storage.
 Secondary memory is slower, cheaper than the primary memory
 It holds the larger amount of data &b it is also call non-volatile memory.
 Some devices are floppy, hard disk drive, CD-ROM (Compact Disc), Pen drive, etc.
3. Output Unit
 Devices used to get the response or result of process from the computer is called output
 The output unit of computer provides the information and the result of computation to the outside
world
 Computer can understand only binary system, so that output device convert into human understand
format
 Output devices: Monitor, Printer, Plotter, and Speaker etc.

Number System
Introduction:
 A number is required for counting or express the amount of some quantity.
 It consists of group of symbols called digits, which are arranged in definite manner.
 There are many ways to digits are arranged to form a number.
 various ways of representing number system:
1. Decimal number system(0,1,2,......9)
2. Octal number system(0,1,2,.....7)
3. Hexadecimal number system(0,1,2,........9,A,B,C,D,E,F)
4. Binary number system(0&1)
 The number of digits in system is called radix or base.

T
 The number systems are basically two types:
a. Non positional number system.

E
b. Positional number system.

.N
a. Non positional number system:
o This method of counting uses non positional number system or additive approach
o Using this system, the symbols are
o I for 1
Disadvantage:
II for 2 III for 3
IA
o It is difficult to perform arithmetic operations.
IIII for 4 etc...,
ND
b. Positional Number System:
o It is uses few symbols called digits.
o Such symbols specify different values depending on the position.
Example: 7734.25(10)
o The base or radix is the total number of digits available in the number system
NI

1. Decimal Number System:


o This system is base 10 or radix 10 number system.
o There contain all 10 numbers.
I

o 0,1,2,3,4,5,6,7,8,9.
.K

o In this representation has two types of digits


1) Most significant digit (MSD)
W

2) Least significant digit (LSD)


o Base of this number system may be represented or not
Example:
W

7293.25
1
5 x 10-2 5 x 100 0.05
W

1
2 x 10-1 2 x 10 0.20
3 x 100 3x1 3.00
9 x 101 9 x 10 90.00
2 x 102 2 x 100 200.00
7 x 103 7 x 1000 7000.00
7293.25
2. Binary Number System:
o In a binary system have only two digits 0&1
o This system is called radix 2 or base 2 systems.
o The computer can works with only binary system
o Because digital pulse represents 1 for high voltage (5v) 0 for low voltage (0v)
o Binary representation:
Position 5 4 3 2 1 -1 -2 -3 -4
Weights 24 23 22 21 20 2-1 2-2 2-3 2-4
Values 16 8 4 2 1 0.5 0.25 0.125 0.0625
Binary representation of some numbers
Decimal Octal Hexadecimal Binary
0 0 0 0000
1 1 1 0001
2 2 2 0010
3 3 3 0011
4 4 4 0100
5 5 5 0101
6 6 6 0110
7 7 7 0111
8 8 1000
9 9 1001
10 A 1010

T
11 B 1011

E
12 C 1100
13 D 1101

.N
14 E 1110
15 F 1111

3) Octal Number System:

Position 5 4 3 2 1
IA
The number system with base 8 or radix 8 is has only 8 digits 0,1,2,3,4,5,6,7.
-1 -2 -3
ND
4 3 2 1 0 -1 -2
Weights 8 8 8 8 8 8 8 8-3
Values 4096 512 64 8 1 0.125 0.0156 0.00195
Example:
Conversion of 2 5 Octal to Binary
NI

010 101 (25)8


I
.K

(25)8 = (010101)2
Conversion of Octal to decimal
5 x 80 5 x 1 5 (25)8
W

2 x 81 2 x 8 16
21
W

(25)8 = (21)10
W

Conversion of Octal to Hexadecimal


2 5 (25)8
1. Convert octal to 010 101 binary

0001 0101
2. Convert 1 5 Binary to Hexadecimal

(25)8 = (15)16
Need for logical analysis & thinking:
 Logical thinking is the process of understanding something logically.
 Only through logical thinking we can achieve the specific goals & targets.
 Logic is the basic form of the concept, judgment and reasoning.
 When finalizing the goal or target of something, we have put together our judgment & reasoning to
reflecting reality.
PROBLEM SOLVING:
 Problem solving can be represented in several ways:
 The following ways:
1) Algorithm
2) Flow chart
3) Pseudo code
4) Decision table
5) Program
1) Algorithm:
 Sequences of instructions that carryout in step by step manner in English language.
2) Flow Chart:
 Pictorial representation of algorithm using standard symbols.
3) Pseudo Code:
 Rules of structured design & programming.
4) Decision Table:

T
 Nested selection to help clarify the conditions to be tested & proper actions.
5) Program:

E
 The algorithm can be represented using high level language.
1) Algorithm:

.N
 Sequence of instructions that carry out in a step by step manner.
 The algorithm is used to refer the logic of the program.
 It is one of the basic tool used to develop the problem solving.

Characteristics:
IA
ND
 Each & every instructions should be precise (perfect)
 The instructions should not be repeated
 Ensure that the algorithm will terminate
 It should be written in sequence.
NI

 It should be in English.
Qualities of good algorithm:
The following factors are considered & measure the good algorithm.
I

1) Time: lesser time will take to execute the program.


.K

2) Memory: lesser memory will take to execute the program.


3) Accuracy: program more accurate results.
4) Sequence: it must form in a sequence.
W

5) Generality: it designed to handle a range of input data to meet criteria.


So that algorithm must be generalized.
2. Flow chart:
W

 It is diagrammatic represents the sequence of operations using standard symbols.


 Draw the diagram oriented representation using symbols like as oval, parallelogram, rectangle, etc....,
W

Aim of flow charts:


 It is easier to understand.
 Easy to analyze &compare various methods.
 It provides effective programming documentation.
 It assists in reviewing & debugging.
 Programming preparation can be simplified using the flow chart.
Flow chart symbols:
E T
.N
IA
ND
I NI
.K
W

Rules for drawing flow chart:


 The standard symbols only are used.
 Flow of procedures is from top to bottom or left to right.
W

 Direction of flow of control must represent.


 Only one line will come & out from the process symbol.
W

 Only one flow line enters to decision symbol, two or three flow will be out.

 Every program must present the start & stop terminal symbol

START
STOP
 Flow lines should not cross each other.
Addition symbols:
E T
.N
IA
ND
Basic design structure:
 Design the structure to getting solution for problem.
 There are three design structures are
1) Sequence
2) Selection
NI

3) Loop
1) Sequence Structure:
 It is the simples because it is series of statements performed one after another
I

 Only one direction of every time execution.


.K

2) Selection Structure:
 Selection structure takes decision for select the control flow
W

 It may be two exist TRUE OR FALSE separately process & rejoin in any point.
 Otherwise TRUE value only process some statement & join in next statement.
3) Loop Structure:
W

 It is used to execute a sequence of steps in number of times until condition is met.


 there are two types of loops:
W

1) Top tested loop


2) Bottom tested loop.
Sequence Structure Selection Structure

START
FALSE TRUE
IF(A>B)
READ
PRINT “B IS BIG” PRINT “A IS BIG”
PROCESS

OUTPUT

STOP
M
1) Top tested loop
 It is evaluated statement is first then TRUE only flows lines goes into loop statements.
 Otherwise FALSE will not enter to loop statements.
2) Bottom tested loop:
 Decision will take at least once loop of statement executed
 After executed loop condition check then TRUE means again enter in to loop otherwise exit the loop.
Top tested loop Bottom tested loop

Initialization

E T
Block of Statements

.N
FALSE Evaluating TRUE

IA OUTPUT
Condition
ND
STOP
NI

Pseudo code:
 It is written in normal English & cannot be understand by the computer.
I
.K

 Set of statements or instructions written in programming language.


 It is also called Program Design Language(PDL)
Rules:
W

 Write one statements per line.


 Capitalize keywords.
 End multiline structure(if,else,while,)
W

 Indent show hierarchy


 Keep statements language independent.
W

Advantages:
 It is simple to use.
Disadvantages:
 It is not visual.
Example:
Pseudo code for Factorial:
Set initial one to F, i
READ N value to find factorial
IF (i<=N) THEN
F=F*i
i=i+1
ENDIF
WRITE the factorial of the number.
Stop

Draw the flow chart to find biggest of two numbers.

START
M

READ A,B
E T
Convert the (756)10 to octal and hexadecimal

.N
Quotient Reminder
756
8
94
8
94

11
4

6
IA
ND
11
1 3
8

(756)10 = (1364)8
NI

Quotient Reminder
756
I

47 4
16
.K

47
2 13
16
W
W

(756)10 = (2D4)16
Find the octal equivalent of the number (10111001100.1101011)2
W

010 111 001 100 . 110 101 100


2 7 1 4 . 6 5 4

(10111001100.1101011)2 = (2714.654)8

Find the decimal equivalent of the hexadecimal number 4D.C8.


(4D.C8)16 = (77.78125)10

1
8 x 16-2 8 x 256 0.03125
1
12 x 16-1 12 x 16 0.75000
13 x 160 13 x 1 13.00000
4 x 161 4 x 16 64.00000
77.78125
How will you convert CAB in hexadecimal to binary?

C A B
1100 1010 1011
(CAB)16 = (110010101011)2
Convert the following numbers into their binary equivalents: FAC16, 5618
FAC16 = (111110101100)2

F A C
1111 1010 1100
(561)8 = (101110001)2

5 6 1
101 110 001

T
Convert the decimal number 59.8125 into binary and octal.

E
59.8125 into binary
Quotient Reminder

.N
59
29 1
2
29
14 1
2
14
2
7 0
IA
ND
7
3 1
2
3
1 1
2
I NI

0.8125 X 2 1.625 1
.K

0.625 X 2 1.25 1
0.25 X 2 0.5 0
0.5 X 2 1.0 1
W

(59.8125)10 = (111011.1101)2
W

59.8125 into octal

Quotient Reminder
W

59
8
7 3

0.8125 X 8 6.5 6
0.5 X 8 4.00 4

(59.8125)10 = (73.64)8
Draw the flow chart and write an algorithm to compute area and circumference of circle.

ALGORITHM: FLOW CHART:


START
Step1: Start the program.
Step2: Get the Radius R as input.
Step3: Find Area and Circumference
READ R
Area  3.14 * R * R
Circumference  2 * 3.14 * R
Step4: Print the Area and Circumference. AREA = 3.14 * R * R
CIRCUMFERENCE = 2 * 3.14 *R
Step5: Stop the program.

Draw the flow chart and write an algorithm to compute the student details.
ALGORITHM: FLOW CHART:
Step1: Start the program.
Step2: Read the Marks for E, T, G, P, C, and M as input. START

T
Step3: Find Total and Percentage
Total  E+T+G+P+C+M

E
Percentage  (Total/1200)*100 READ E, T, G, P, C, M
Step4: Print the Total and Percentage.

.N
Step5: Stop the program.
Total = E+T+G+P+C+M
Percentage = (Total/1200)*100
IA PRINT Total,
ND
Percentage

STOP
NI

Write an algorithm, Flow chart and psuedocode to compute factorial of a number.


ALGORITHM: FLOW CHART:
I

Step1: Start the program. START


.K

Step2: Read the n as input.


Step3: Set initial values F = i= 1.
Step4: IF i<=n else goto Step5
W

READ N
Step4.1: F  F * i
Step4.2: i  i + 1
Step5: Goto step4.
W

F=i=1
Step6: Otherwise print the F.
Step7: Stop the program.
W

FALSE TRUE
IF (i<=N)

PRINT F F=F*i
i=i+1
STOP

Draw a flow chart to find sum first 100 natural numbers.


ALGORITHM: FLOW CHART:
Step1: Start the program.
Step2: Set initial values SUM = i= 0. START
Step3: IF i<=100 else goto Step5
Step3.1: SUM  SUM + i
Step3.2: i  i + 1 SUM = i = 0
Step4: Goto step3.
Step5: Otherwise print the SUM.
Step6: Stop the program.

Draw the flow chart and write an algorithm to find roots of quadratic equation.

E T
ALGORITHM: FLOW CHART:
Step1: Start the program. START

.N
Step2: Read the values for a, b, c as input.
Step3: Find the value of D.
D  b * b – (4 * a * c) READ a,b,c
Root1 (-b + sqrt(D)) /(2 * a)
Root2 (-b - sqrt(D)) /(2 * a)
IA
Step4: IF D is greater than or equal to zero than find the roots

D = b * b – (4 * a * c)
ND
Step5: Print the Root1, Root2.
Step6: IF D is not greater than or equal to zero,
then print roots are imaginary.
FALSE IF (D>=0) TRUE
Step7: Stop the program.
NI

Root1 = (-b + sqrt(D)) /(2 * a)


I
.K

Root2 = (-b - sqrt(D)) /(2 * a)


PRINT Roots
are Imaginary
W

PRINT Root1,
Root2
W
W

STOP

UNIT-2
History of ‘C’ language:
 ‘C’ is one of the most popular programming languages; it was developed by Dennis Ritchie
at AT & T’s Bell Laboratories at USA in 1972.
‘C’ IS A MIDDLE LEVEL LANGUAGE
 Low level language:
o Low level language is in terms of 0’s and 1’s.
o ‘C’ language has the certain features of “low-level language” that allows the
programmer to carry out operations on bits that are normally available in assembly or
machine language.
 High level language:
o High level language looks like normal English, whose instruction set is more
compatible with human languages.
o These languages are machine independent. Ex are FORTRAN, PASCAL, COBOL,
BASIC, C, C++,…..etc
 C stands in between these two categories. It is neither a low level language nor a high level
language. It is a middle level language.

T
 It means it performs the task of low level language as well as high level language.
 We can write the codes for operating system, application programs, and assembly language

E
programs in ‘C’ language.

.N
 UNIX operating system is written in ‘C’ language.

FEATURES AND APPLICATIONS OF ‘C’ LANGUAGE:


IA
1. ‘C’ is a general purpose, structured programming language.
2. ‘C’ is powerful, efficient, compact, portable and flexible.
3. ‘C’ is well suited for writing system software as well as application software.
ND
4. ‘C’ program can be run on different operating systems of the different computers with little
or no alteration.
5. ‘C’ is a middle level language, i.e, it supports both the low level and high level language
NI

features.
6. ‘C’ language allows manipulation of data at the lowest level i.e bit level manipulation. This
feature is extensively useful in writing system software program.
I

7. ‘C’ is a widely available, commercial ‘C’ compilers are available on most PC’s.
.K

8. ‘C’ programs are fast and efficient.


9. ‘C’ has got rich set of operators.
10. ‘C’ can be applied in systems programming areas like compilers, Interpreters and Assemblers
W

etc.
W

STRUCTURE OF A ‘C’ PROGRAM


Documentation section
W

Preprocessor section
Definition section
Global declaration section
Void Main()
{
Declaration part;
Executable part;
}
Sub program section
{
Body of the sub program;
}
Documentation section:
 It contains a set of comment lines used to specify the name of program the author and
other details etc.,
Comments:
 Comments are very helpful in identifying the program features and underlying logic of
the program.
 The single line comments using “\\”.
 The lines begins with ‘/*’ and ending with ‘*/’ are known as comment lines. These are
not executable, the compiler is ignored anything in between /* and */.
Preprocessor section:
 It is used to link system library files for defining the macros and for defining the
conditional inclusion.
Eg: #include<stdio.h>, #define A 10, #if def, #endif….etc.
Global declaration section:
 The variables that are used in more than one function throughout the program are called
global variables and declared outside of all the function i.e., before main().
 Every ‘C’ program must have one main() function, which specify the starting of ‘C’
program. It contains the following two parts.

T
Various elements of ‘C’ program:

E
Comment: /* program for temperature conversion */
Header file: #include<stdio.h>

.N
Preprocessor directories: #define con 1.8 //Constant
Reserved words: int main ()
{
Variable type: float c,f IA //Standard identifiers
printf(“enter the Celsius values…….”);
scanf(“%f”, &c);
ND
Control string:
Special character: f = (con * c)+32;
Execution character: printf(“\n Fahrenheit value of the given %f Celsius value is
%f”, c,f);
NI

Reserved word: return(0);


}
Declaration part:
I

 This part is used to declare all the variables that are used in the executable part of the
.K

program and these are called local variables.


Executable part:
 It contains atleast one valid ‘C’ statement.
W

 The execution of a program begins with opening brace ‘{‘and ends with closing brace
‘}’.
W

 The closing brace of the main function is the logical end of the program.
 All the statements in the program ends with a semicolon(;) except conditional and control
W

statements.

PROGRAMMING RULES:
 All statements in ‘C’ program should be written in lower case letters.
 Blank spaces may be inserted between the words. It is not used while declaring a variable,
keyword, constant and function.
 The program statement can write anywhere between the two braces following the declaration
part.
 The user can also write one or more statements in one line separating them with a
semicolon(;).

EXECUTING A ‘C’ PROGRAM


 Execution is the process of running the program, to execute a ‘C’ program we need to
follow the steps given below.
1. Creating the program.
2. Compiling the program.
3. Linking the program with system library.
4. Executing the program.
Creating the program:
 It means entering and editing the program in standard ‘C’ editor and save the program with
.C as an extension.
Compiling the program:
 This is the process of converting the high level language program into machine
understandable form(Machine language). For this purpose compiler is used.
 Usually this can be done in ‘C’ language by pressing ALT+F9 or choose compile option in
the menu system.
 Here there is a possibility to show errors i.e., syntax errors, means the statements written in
program are not in proper syntax.
Linking the program with system library:
 ‘C’ language program is the collection of predefined functions. These functions are already

T
written in some standard ‘C’ header files. Therefore before executing a ‘C’ program, we

E
need to link with system library. This can be done automatically at the time of execution.
Executing the program:

.N
 This is the process of running and testing the program with sample data. At this time there
is a possibility to show two types of errors given below.
Logical errors: these are the errors, in which the conditional and control statements cannot end
their match after some sequential execution. IA
Data errors: these are the errors, in which the input data given, is not in a proper syntax as
ND
specified in input statements.
 Usually executing the program can be done by pressing CTRL+F9 or choose run option
from the menu system.
NI

‘C’s CHARACTER SET


 The character set is the any language and they are used to represent information.
 Like natural languages, computer language will also have well defined character set, which
I

is useful to build the programs.


.K

 Thus learn to combine these alphabets to plan for words which in turn are combined to
form sentences and sentences are combined to form paragraphs.
W

 Similarly the characters used to write ‘C’ program are basically of two types, namely
i. Source character set
ii. Execution character set
W

Source character set


 These are used to construct the statements in the source program.
W

 These are of four types


Source character Notation
set
Alphabets A to Z and a to z
Decimal digits 0 to 9
White spaces Blank space, horizontal tabs, vertical tab, new line, form feed.
Special characters +, -, *, /, ;, ~, < , > , {, }, =, @, % .

Execution character set:


 These are employed at the time of execution. This set of characters are also called as non
graphic characters because, these characters are invisible and cannot be printed or
displayed directly.
 These characters will have effect only when the program is being executed.
 Execution characters set are always represented by a backslash(\) followed by a character.
 These are also called as ‘escape sequences’.
Character Escape sequence Result
Bell(Alert) \a Beep sound
Backspace \b Moves previous position
Horizontal tab \t Moves next horizontal tab
Vertical tab \v Moves next vertical tab
New line \n Moves next line
Form feed \f Moves initial position of next page
Carriage return \r Moves beginning of the line

C TOKENS:
 The tokens are usually referred as individual text and punctuation in a passage of text.
 The ‘C’ language program can contain the individual units called the C tokens and has
the following types.
1. Identifiers
2. Keywords

T
3. Constants

E
4. Strings
5. Operators

.N
6. Special symbols

1. IDENTIFIERS
IA
 Identifiers are names given to various program elements, such as variables, functions and
arrays etc.
ND
Rules:
 Identifiers consist of letters and digits in any order.
 The first character must be a letter/character or may begin with underscore( _ ).
 Both upper/lower cases are permitted although uppercase character is not equivalent to
NI

corresponding lowercase character.


 The underscore ‘ _’ can also be used and is considered as a letter.
 An identifier can be of any length while most of the ‘C’ compiler recognizes only the first
I
.K

31 characters.
 No space and special symbols are allowed between the identifier.
 The identifier cannot be a keyword.
W

Valid identifiers:
STDNAME, SUB, Y2K.
W

Invalid identifiers:
STD NAME, Return, $stay, 7rno.
W

2. KEYWORDS:
 There are certain reserved words called keywords that have standard and predefined
meaning in ‘C’ language which cannot be changed and they are the basic building blocks
for program statements.
 Keywords are must written in lower case.
 The ‘C’ keywords are listed below.
1. auto 9. double 17. int 25. struct
2. break 10. else 18. long 26. switch
3. case 11. enum 19. register 27. typedef
4. char 12. extern 20. return 28. union
5. const 13. float 21. short 29. unsigned
6. continue 14. for 22. signed 30. void
7. default 15. goto 23. sizeof 31. volatile
8. do 16. if 24. static 32. while
Data types:
 Data type is the type of the data, that are going to access within the program.
 Each data type may have predefined memory requirement and storage representation.
Primary User defined Derived Empty
char Arrays
int pointer void
float typedef structures
double union
The bytes occupied by each of the primary data types are
Data type Description Memory Control Ex
string
int Integer quantity 2 bytes %d int a=39;
char Single character 1 byte %c char s = ‘n’;
float Floating pointing no’s. 4 bytes %f float f=29.77
double Double floating pointing 8 bytes %lf double d=
no’s. 29771770776

T
 All C compilers supports the five fundamental data types called int, char, float, double

E
and void.
 The primary data types are divided into the following.

.N
INTEGER TYPE
 Integers are the numbers with the supported range.
 Usually the integers occupy one word of storage typically 16 or 32 bits.

signed unsigned
IA
 The size of the integer depends upon the system.
ND
int unsigned int
short int unsigned short int
long int unsigned long int
CHARACTER TYPE
NI

 Characters are generally stored in 8 bits and a single character can be defined as char data
type.
I

char signed char unsigned


.K

FLOAT TYPE char


 The floating point numbers are generally stored in 32 bits with the 6 digits of precision.
 The double datatype uses the 64bits with the 14 digits of precision.
W

float double long double


EMPTY DATA TYPE
W

 The void is the null data type in ‘C’ language.


 This is generally specified with the function which has no arguments.
W

void
VARIABLES:
 A variable is an identifier that is used to represent some specified type of information.
 Variable name give to relate the program.
i) Variable declaration:
 We must declare them in a program, and this declaration tells the compiler what the
variable name and type of the data that the variable will hold.
Syntax: datatype variable-1,variable-2,…,variable-n;
Example: int code; char sex; float price;
ii) Initializing variables:
 Initialization of variables can be done using the assignment operator ( = ).
Syntax: Datatype Variable = value;
Example: int i=29;

SCOPE OF VARIABLES:
Local variables:
 The variables which are defined inside a main function block or inside a function are
called local variables.
 It is declared within blocks.
Example:
void main()
{
int i,j;
/* body of the function */
}
Global variables:
 The variables that are declared before the function main() are called the global variables.
Example:
int a=5,b=2;

T
void main()

E
{
fun();

.N
}
void fun()
{

}
int sum;
sum = a+b;
IA
ND
STORAGE CLASSES:
1. Auto:
 They are called as the automatic because their memory space is automatically allocated
NI

as the variable is declared.


 It is optional keyword.
I

Syntax: Storage_class_type data_type var1, var2……var n;


.K

Example: auto int a,b;


2. Static:
 The static variables are the variables for which the contents of the variables will be
W

retained throughout the program.


 These are permanent within the function in which they are declared.
W

Syntax: Storage_class_type data_type var1, var2,…….varn;


Example: static int a,b;
W

3. Extern:
 The external variables are declared out of the main() function the availability of these
variables are throughout the program and that is both in main program and inside the user
defined functions.
Syntax: Storage_class_type data_type var1, var2,……var n;
Example: extern int a, b;
4. Register:
 Registers are special storage areas within a computer’s central processing unit.
 The actual arithmetic and logical operation that comprise a program are carried out
within these registers.
Syntax: Storage_class_type data_type var1, var2, ………..var n;
Example: register int a,g;

CONSTANTS:
 The item whose values cannot be changed during the execution of program are called
constants.
a) Numeric constants:
i) Integer constants:
 An integer constant formed with the sequence of digits.
 There are three types of integer constants which forms different number system.
Syntax: const datatype identifier=value;
Example: const int M = 95;
Rules:
 It must have atleast one value.
 Decimal point is not allowed.
 It can be either positive or negative.
ii) Real constants:
 A real constant is made up of a sequence of numeric digits with presence of a decimal

T
point.

E
 Real constants serve as represent quantities such as distance, heights, temperatures, etc.
Syntax: const datatype identifier=value;

.N
Example: const float distance =126.5;
Rules:
 A real constant must have one digit.
 A real constant must have decimal point.
 No commas or blank spaces are allowed.
IA
ND
b) Character constants:
i) Single character constants:
 The character constant contains a single character enclosed within pair of single inverted
commas(‘) both pointing to the left.
NI

Syntax: const datatype identifier= value;


Example: const char c=’s’,gender=’F’;
ii) String constants:
I

 A string constant is a sequence of characters enclosed in double quotes the characters


.K

may be letters, numbers, special characters and blank spaces etc.


Syntax: const datatype identifier= value;
W

Example: const char c[10]=”senthil”;


W

Delimiters:
These are the symbols, which has some syntactic meaning and has got significance.
Symbol Name Meaning
W

# Hash Pre-processor directive


, Comma separate list of variables
: Colon Label
; Semi colon Statement end
() Parenthesis Function and Expression
{} Braces Creating blocks
[] Square bracket Arrays

Statements:
 Statements can be defined as set of declaration or sequence of action. Statement causes
the computer to perform some action.
1. Assignment statements:
 Assignment operator used for assigning values to the variables.
Example: basic =3890;
2. Null statements:
 A statement without any characters and it has only semicolon is called null statement.
Example: ; (null statement)
3. Block of statements:
 Block contains several statements that are enclosed within a pair of braces {}.
 These can be any of expression, assignments and keywords etc.
Example:
{
int a=890;
float b= 89.9;
printf(“%d%f”, a, b);
}
4. Expression statements:
 These consist of expressions and can be arithmetic, relational or logical.
Example:
a= 29

T
B=a+77;

E
fun(a,b);

.N
OPERATORS
 An operator is as symbol that specifies an operation to be performed on the operands.
 The data items are called operands.
Example: a+b
IA
‘+’ operator and a, b are the operands.
ND
Types of operators:
1) Arithmetic Operator (+, -,*,/,%,)
2) Relational Operator (<,>,<=,>=,!=,==)
NI

3) Logical Operators (&&.||,!)


4) Assignment Operator ( = )
5) Increment & decrement Operator (++,--)
I

6) Conditional (or) Ternary Operator (? , : )


.K

7) Bitwise Operator (&,!,|,^)


8) Special Operator (, sizeof,&&*, .&->)
W

1) Arithmetic operators:
 Basic arithmetic operation like addition, subtraction, multiplication, and division.
Operator Meaning Example A=9, B=5
W

+ addition C=a+b C=14


- subtraction C=a-b C=4
W

* multiplication C=a*b C=45


/ division C=a/b C=1
% Modulo C=a%b C=4

Example:
//Arithmetic Operators
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d;
clrscr();
printf("Arithmetic Operators");
printf("\nEnter the A & B Value:");
scanf("%d%d",&a,&b);
printf("A=%d\nB=%d",a,b);
c=a+b;
printf("\nAddition = %d",c);
c=a-b;
printf("\nSubtraction = %d",c);
c=a*b;
printf("\nMultiplication = %d",c);
c=a/b;
printf("\nDivision = %d",c);
c=a%b;
printf("\nModulo = %d",c);
getch();
}
OUTPUT:
Arithmetic Operators

T
Enter the A & B Value:9
5

E
A=9

.N
B=5
Addition = 14
Subtraction = 4
Multiplication = 45
Division = 1
Modulo = 4
IA
ND
Unary arithmetic: it requires only one operand.
Ex: +x
Binary arithmetic: it requires two operands.
NI

Ex: a+b
I

2) Relational operators:
.K

 Relational operators are used to compare two or more operands.


 Operands may be variables, constants or expression.
 The value of relational expression is either one or zero.
W

 Relational operators are used in decision making process.


Operator Meaning Example A=9, B=5
W

< Less than C=a<b C=0


> Greater than C=a>b C=1
<= Less than or Equal to C=a<=b C=0
W

>= Greater than or equal to C=a>=b C=1


== Equal to C=a==b C=0
!= Not equal to C=a!=b C=1
Example:
//Relational Operators
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Relational Operators");
printf("\nEnter the A & B Value:");
scanf("%d%d",&a,&b);
printf("A=%d\nB=%d",a,b);
c=a>b;
printf("\nGreaterthan (>)= %d",c);
c=a<b;
printf("\nLessthan (<)= %d",c);
c=a>=b;
printf("\nGreaterthan or equal (>=)= %d",c);
c=a<=b;
printf("\nLessthan or equal (<=)= %d",c);
c=a==b;
printf("\nEqual to (==)= %d",c);
getch();
}
OUTPUT:
Relational Operators

T
Enter the A & B Value:9
5

E
A=9

.N
B=5
Greaterthan (>)= 1
Lessthan (<)= 0
Greaterthan or equal (>=)= 1
Lessthan or equal (<=)= 0
Equal to (==)= 0
IA
ND
3) Logical operators:
 Logical operators are used to combine the results of two or more conditions.
 The logical operators are &&, ||,!
NI

Syntax: (exp1)&&(exp2)
Operator Meaning Example A=9, B=5, C=2
I

&& Logical AND d=(a>b)&&(a>c) d=1


.K

|| Logical OR d=(a>b)||(a>c) d=1


! Logical NOT d=!(a>=b) d=0
W

Example:
//Logic Operators
#include<stdio.h>
W

#include<conio.h>
void main()
{
W

int a,b,c,d;
clrscr();
printf("Logic Operators");
printf("\nEnter the A,B,C Value:");
scanf("%d%d%d",&a,&b,&c);
printf("A=%d\nB=%d\nC=%d",a,b,c);
d=(a>b)&&(a>c);
printf("\nLogic AND\n((a>b)&&(a>c)) = %d",d);
d=(a>b)||(a>c);
printf("\nLogic OR\n((a>b)||(a>c)) = %d",d);
d=!(a>=b);
printf("\nLogic NOT\n(!(a>=b)) = %d",d);
getch();
}
OUTPUT:
Logic Operators
Enter the A,B,C Value:9
5
2
A=9
B=5
C=2
Logic AND
((a>b)&&(a>c)) = 1
Logic OR
((a>b)||(a>c)) = 1
Logic NOT
(!(a>=b)) = 0

4) Assignment operators:

T
 Assignment operators are used to assign a value or an expression or a value of a variable
to another variable.

E
Example: x=5;

.N
i) Compound assignment:
 Compound assignment operators to assign a value to a variable in order to assign a new
value to a variable after performing a specified operation.
Example: x+ = y
ii) Nested assignments:
IA
 ‘C’ language has got distinct features in assignment called nested assignment.
ND
Syntax:
var1=var2=…………..var-n= single variable or expression or value;
Example: i=j=k=l;
x=y=z=(i+j+k);
NI

5) Increment or decrement operators:


I

 ++ and -- are the increment and decrement operator.


.K

 These operators are called unary operators.


 Pre increment or pre decrement: First increment or decrement the value after assign or
W

operate.
 post increment or post decrement: Assign or operate after increment or decrement
Operator Meaning Example A=5
W

++a Pre increment printf(“A=%d”,++a) A=6


--a Pre decrement printf(“A=%d”,--a) A=5
printf(“A=%d”,a++) A=5
W

a++ Post increment


a-- Post decrement printf(“A= %d”,a--) A=5

6) Conditional operator:
 It checks the condition and executes the statement depending on the condition.
 It is like as if…else statement.
Syntax:
Condition?exp1:exp2;
Example:
int a=5,b=3,big;
big=a>b?a:b;
printf(“%d is big”,big);

7) Bitwise operators:
 It is used to manipulate the data at bit level.
 It operates on integer only.
 It may not be applied to float or real.
a) Bitwise AND(&):
 This operator is represented as ‘&’ and operates on two operands of integer type.
 Truth table for &:
A B A&B
0 0 0
0 1 0
1 0 0
1 1 1
b) Bitwise OR(|):
 This operator gives if either of the operand bit is ‘|’ then result is ‘1’ or both operands are
1’s then also given ‘1’.
A B A|B

T
0 0 0
0 1 1

E
1 0 1
1 1 1

.N
c) Bitwise exclusive OR(^):
 Similar to AND operator in all aspects but integer gives if either of the operand bit is
high(1) then
 If both
low(0)
IA it gives high(1) result.
operand bits are same then it gives
result.
ND
I NI
.K
W

For all the above operators in all possible combinations of bits as shown below.
A B A|B A&B A^B ~A
W

0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 0 1 0
W

1 1 1 1 0 0
Example:
//Bitwise OPerators
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Bitwise Operators");
printf("\nEnter the A & B Value:");
scanf("%d%d",&a,&b);
printf("A=%d\nB=%d",a,b);
c=a&b;
printf("\nBitwise AND (&) = %d",c);
c=a|b;
printf("\nBitwise OR (|) = %d",c);
c=a^b;
printf("\nBitwise EX-OR (^) = %d",c);
c=~a;
printf("\nOne's Complement or Bitwise NOT (~) = %d",c);
c=a<<2;
printf("\nLeft Shift (<<)= %d",c);
c=a>>2;
printf("\nRight Shift (>>)= %d",c);
getch();
}
OUTPUT:
Bitwise Operators
Enter the A & B Value:7

T
3
A=7

E
B=3

.N
Bitwise AND (&) = 3
Bitwise OR (|) = 7
Bitwise EX-OR (^) = 4
One's Complement or Bitwise NOT (~) = -8
Left Shift (<<)= 28
Right Shift (>>)= 1
IA
ND
8) The special operator:
1. Comma operator(,):
 It is used to separate the statement elements such as variables, constants or expression
etc.
NI

Example: val = (a=3, b=9, c=77, a+c);


2. Sizeof() operator:
 it is a unary operator, that returns the length in bytes of the specified variable, and it is
I
.K

very useful to find the bytes occupied by the specified variable in the memory.
 It is a compile time operator.
Syntax:
W

sizeof(var);
Ex:
W

void main()
{
int a;
W

printf(“size of variable a is……..%d”, sizeof(a));


}
Output:
size of variable a is…………2
3. Pointer operators:
&---This symbol specifies the address of the variable.
* --- This symbol specifies the value of the variable.
4. Member selection operators:
. and -- > : These symbols used to access the elements from a structure.

EXPRESSIONS:
 An expression represents data item such as variables, constants and are interconnected
with operators as per the syntax of the language.
 An expression is evaluated using assignment operator.
Syntax: variable = expression;
Example: x=a*b-c;
Arithmetic operator’s precedence:
 Arithmetic operators are evaluated from the left to right using the precedence of operators
when the expression is written without the parameters.
High:* / %
Low: + -
 First phase: the highest priority operators are evaluated in the expression.
 Second phase: the lowest priority operators are evaluated in the expression.

Type conversion:
 It refers to the process of changing an entity of one data type into another.
i) Implicit conversion:
 It is an automatic type conversion. In a mixed type expression data of one or more subtypes

T
can be converted to a super type as needed at runtime so that the program will run correctly.

E
Example:
int c;

.N
float f=3.5;
c=f;
printf(“%d”,c);
OUTPUT:
3
IA
ND
ii) Explicit conversion:
 The explicit conversion can be made possible to convert one data type to another by
forcefully and it is different from the implicit conversion.
Syntax: var1=(datatype)var2;
NI

Ex: int a=10;


float(a);
Where a=10;
I

float (a) will contain 10.000000


.K

MANAGING INPUT AND OUTPUT OPERATIONS


W

INPUT OUTPUT STATEMENTS


 We know that input, process, output are the three essential features of computer program.
 The program takes some input data processes it and gives the output.
W

 We have two methods for providing data to the program.


o Assigning the data to the variables in a program.
W

o By using the Input/Output statements.


 In ‘C’ language, two types of Input/Output statements are available, and all input and output
operations are carried out through function calls.
 Several functions are available for input/output operations in ‘C’.
 These functions are collectively known as the standard I/O library.
i) Unformatted Input/Output statements
ii) Formatted Input/Output statements
Input / Output

Unformatted I/O Formatted I/O

Input Output Input Output


getchar() putchar() scanf() printf()
getc() putc() fscanf() fprintf()
gets() puts()
getch()
UNFORMATTED INPUT/OUTPUT STATEMENTS
1) getchar() function:
 A single character can be given to the computer using ‘C’ input library function getchar().
Syntax: char variable = getchar();
Example: char x;
x= getchar();
 The getchar() function is written in standard I/O library.
 It reads a single character from a standard input device.
 This function do not require any arguments, through a pair of empty parenthesis, must follow

T
the statement getchar().

E
2) putchar() function:
 The putchar() function is used to display one character at a time on the standard output

.N
device.
Syntax: putchar(char variable);
Example: char x;
putchar(x);
3) getc() function:
IA
 This is used to accept a single character from the standard input to a character variable.
ND
Syntax: char variable = getc();
Example: char c;
c= getc();
NI

4) putc() function:
 This is used to display a single character in a character variable to standard output device.
Syntax: putc(char variable);
I

Example: char c;
.K

putc(c);
5) gets() function:
 The gets() function is used to read the string from the standard input device.
W

Syntax: gets(char type of array variable);


Example: gets(s);
W

6) puts() function:
 The puts() function is used to display/write the string to the standard output device(Monitor).
W

Syntax: puts(char type of array variable);


Example: puts(s);
7) getch() function:
 The getch reads a single character directly from the keyboard without echoing to the screen.
Syntax: int getch(void);
8) getche() function:
 The getche reads a single character from the keyboard and echoes it to the current text
window.
Syntax: int getche(void);

Character test functions:


Function Test
isalnum(ch) Is ch an alphanumeric character?
isalpha(ch) Is ch an alphabetic character?
isdigit(ch) Is ch a digit?
islower(ch) Is ch a lowercase letter?
toupper(ch) Convert ch to uppercase.
isupper(ch) Is ch a uppercase letter?
isspace(ch) Is ch a blank space character?
tolower(ch) Convert ch to lowercase.

FORMATTED INPUT/OUTPUT STATEMENTS:


 Formatted input/output refers to input and output, that has been arranged in a particular
format.
INPUT OUTPUT
scanf() printf()
fscanf() fprintf()
a) scanf() function:

T
 Input data can be entered using the standard input library function called scanf().
 This function is used to enter any combination of input.

E
 The scanf() function is used to read information from the standard input device, scanf() starts

.N
with a argument and may contain additional arguments.
Syntax: scanf(“control string”, &var1,…………&var-n);
Example: int n;

Control string:
scanf(“%d”, &n); IA
 It is the type of data to accept via the input statements, this can be formatted and always
ND
preceded with a ‘%’ sign.
Format code Meaning
%c Single character
NI

%d integer
%s Strings
%f Float values
I
.K

Rules:
 The control string must be preceded with % sign and must be within quotations.
 If there is a number of input data items, items must be separated by commas and must be
W

preceded with & sign except for string input.


 The control string and the variables going to input should match with each other.
 It must have termination with semicolon.
W

b) printf() function:
 Output data or result of an operation can be displayed to a standard output device using the
W

library function printf().


 This function is used to output any combination of data.
 It is similar to the input function scanf(), except that it display data rather than input.
 There are two types of printf() functions:
1. printf() with control string
2. printf() without control string
Syntax: printf(“control string”, var1, var2,…………var n);
Example: printf(“result is…….%d”, n);
printf(“%f”,f);
printf(“%s”,s);
Rules:
 The variable must be separated by commas, and need not be preceded with ‘&’ sign.
 The control string and the variables must match in their order.
 The control string must be in quotations and there also use any other text to print with data.
 Provide blank space in between the numbers for better readability.
 Print special messages wherever required in output.
fscanf() and fprintf():
 fscanf() and fprintf() functions are used only during the file operations.
 fscanf()---for reading the content from file.
 fprintf()---for writing the content to the file.

Reading and writing integer numbers:


 The integers can be read/write through the scanf() and printf() statements with the field
specification along with the control string.
Reading:
 The scanf() function reads the integer numbers using its format specification ‘%d ’
Syntax: scanf(“%d” , &var);

T
Example: scanf(“%d%d”, &x, &y);

E
Writing:
 The integer data values can also be displayed using the field width specification in

.N
printf() statement.
Syntax: printf(“%d”, var);
Example: printf(“%d”, x);

Reading and writing real or floating point numbers:


IA
ND
Reading:
 The scanf() function reads the real numbers using its format specification ‘%f ’
Syntax: scanf(“%f” , &var);
Example: scanf(“%f%f”, &x, &y);
NI

Writing:
 The writing or displaying of real numbers may be displayed in decimal point notation
using the field width specification.
I

Syntax: printf(“%(width)f” , var);


.K

Example: printf(“%.2f”,x);
W

Reading and writing character strings:


 The single character or string can be read/write through the scanf() and printf()
statements with the field specification along with the control string.
W

Reading a character:
 The specification for reading character is %c
W

Syntax: scanf(“%c”, var);


Example: scanf(“%c”, gender);
Reading strings:
 Specification for reading string is %s
Syntax: scanf(“%s”, var);
Example: scanf(“%s”, name);
Writing a character:
 A single character can be displayed in a desired position using the following format.
Syntax: printf(“%c”, var);
Writing strings:
 The writing or displaying of string may be displayed in decimal point notation using the
following width specification.
Syntax: printf(“ %s”, var);

Enhancing the readability of output:


 Specify the blank spaces in between the data items whenever necessary and applicable.
 Specify the appropriate headings and names for the variables.
 Give the blank line as and when required.
 Specify newline character whenever is applicable.
 Print special text messages depending on necessity.

CONTROL STATEMENTS OR CONTROL STRUCTURES


 Programmers can take decisions in their program with help of control statements.
 Types of control statements:
1. Sequence (or) Linear Structure
2. Decision making (or) selection (or) Branching Structure
3. Looping (or) Iteration Structure

T
4. Unconditional Structure

E
S.No. Structure Name Types
1 Sequence (or) Linear Structure one by one

.N
1. Simple if
2. If ….else
3. Nested if ….else
2
IA
Decision making (or) Selection (or) Branching Structure
4. if……else ladder
5. Switch case
6. Nested switch case
ND
1. while
2. do-while
3 Looping (or) Iteration Structure
3. for
NI

4. Nested for
1. break
2. continue
4 Unconditional Structure
I

3. goto
.K

4. return
1. Sequence (or) Linear Structure:
 Statements are read one by one is called sequence or linear structure.
W

 It is normal flow of program.


 Only one direction of every time execution.
W

2. Decision making (or) selection (or) Branching Structure


a) Simple if statement
 The if statement is a decision making statement.
W

 It is used to control the flow of execution of the statements and also used to test logically
whether the condition is true or false.
 It is always used in conjunction with condition.
 This statement is used when a question requires answer.
Syntax Flow Chart Example
if(condition is true) #include<stdio.h>
{ Start #include<conio.h>
True statements; void main()
} {
Read A,B
Next Statement; int a,b;
clrscr();
True scanf(“%d%d”,&a,&b);
if(A>B)
if(a>b)
Print “A is Big”
{
False printf(“A is big”);
}
printf(“\nIt is simple if”);
getch();
Print “It is simple if” }

E T
Stop

.N
Properties:
 If the condition is true then the simple or compound condition statements are executed.
 If the condition is false it does not do anything. IA
 The condition is given in parenthesis and must be evaluated as true or false.
 If a compound structure is provided it must be enclosed in opening and closing braces.
ND
b) The if-else statement:
 It is basically two way decision making statement and always used in conjunction with
condition.
 It is used to control the flow of execution and also used to carry out the logical test and
NI

then pickup one of the two possible actions depending on the logical test.
Syntax Flow Chart Example
I

if(condition) //Biggest of 2 Numbers


.K

{ Start #include<stdio.h>
True statements; #include<conio.h>
W

} Read A,B void main()


else {
{ int a,b;
W

False statements; FALSE TRUE clrscr();


if(A>B)
} scanf(“%d%d”,&a,&b);
W

Next Statement; if(a>b)


PRINT “B IS BIG” PRINT “A IS BIG” {
printf(“A is big”);
}
else
{
printf(“B is big”);
}
Print “It is if…else”
printf(“\nIt is if…else”);
getch();
Stop }

c) Nested if……..else statement:


 When a series of if…..else statements are occurred in a program, we can write an entire
if…..else statement in another if….else statement called nesting and the statement is
called nested if.
Start
WWW.VIDYARTHIPLUS.COM
Flow Chart:
Read A,B,C

FALSE TRUE
if(A>B||C>B)

FALSE TRUE
if(A>C)
PRINT “B IS BIG”
PRINT “C IS BIG” PRINT “A IS BIG”

T
Print “It is Nested if…else”

E
Stop

.N
Syntax Example
if(condition 1) //Biggest of 3 Numbers
{
if(condition 2)
{
#include<stdio.h>
#include<conio.h>
void main()
IA
ND
True statement2; {
} int a,b,c;
else clrscr();
{ scanf(“%d%d%d”,&a,&b,&c);
NI

False statement2; if(a>b||c>b)


} {
I

} if(a>c)
.K

else {
{ printf(“A is big”);
False statement1; }
W

} else
Next Statement; {
W

printf(“C is big”);
}
}
W

else
{
printf(“B is big”);
}
printf(“\nIt is Nested if…else”);
getch();
}
d) if……else ladder:
 Nested if statements can become quite complex.
 More than three alternatives is not consistent to determine the logical structure of if
statement.
 In situations, you can use the nested if as the else if ladder.
Flow Chart:
Start

Read A,B,C,D

FALSE TRUE
WWW.VIDYARTHIPLUS.COM

E T
.N
Syntax
if(condition 1)
IA Example
//Biggest of 4 Numbers
ND
{ #include<stdio.h>
Statement 1; #include<conio.h>
} void main()
else if(condition 2) {
NI

{ int a,b,c,d;
Statement 2; clrscr();
scanf(“%d%d%d%d”,&a,&b,&c,&d);
I

}
.K

else if(condition 3) if(a>b&&a>c&&a>d)


{ {
Statement 3; printf(“A is big”);
W

} }
else else if(b>c&&b>d)
W

{ {
Default- statements; printf(“B is big”);
} }
W

Next Statement; else if(c>d)


{
printf(“C is big”);
}
else
{
printf(“D is big”);
}
printf(“\nIt is if…else Ladder”);
getch();
}

The switch statement:


 The switch statement is used to pickup or execute a particular group of statements from
several available groups of statements.
 It allows us to make a decision from the number of choices.
 It is a multiway decision statement, it tests the value of given variable or expression
against a list of case valuesStart
and when a match is found a block of statements associated
with that case is executed.
Flow Chart:
Initialize A=10,B=20,C=0,CH
CH=1
Print C=A+B
Print “1.ADD
2.SUB 3.MUL 4.DIV” CH=2
Print C=A-B

CH=3
Read CH Print C=A*B

CH=4

T
Print C=A/B
switch(CH)

E
.N
Stop
IA
ND
Syntax:
Syntax Example
switch(expression) //Arithmetic operations using switch case
{ #include<stdio.h>
NI

case constant-1: #include<conio.h>


Block 1; void main()
I

break; {
.K

case constant-2: int a=10,b=20,ch,d;


Block 2; clrscr();
break; printf("1.ADD\n2.SUB\n3.MUL\n4.DIV");
W

. printf("\nEnter your choice:");


. scanf("%d",&ch);
W

default: switch(ch)
Default block; {
break; case 1:
W

} printf("%d",a+b);
Next Statement; break;
case 2:
printf("%d",a-b);
break;
case 3:
printf("%d",a*b);
break;
case 4:
printf("%d",a/b);
break;
default:
printf("\nEnter the correct choice");
break;
}
printf("\nIt is switch case");
getch();
}

E T
.N
Rules:
IA
 The expression in switch statement must be an integer value or a character constant.
 No real numbers are used in an expression.
ND
 The case labels must be constants.
 The switch can be nested.
Nested switch() case:
 ‘C’ supports the nested switch() statements. The inner switch() statement can be a
NI

part of an outer switch() statement.


 The inner and outer switch() case constants may be same.
I

 No conflict arises even if they are same.


.K

Comparison of switch() case and nested if:


Switch() case Nested if
W

The switch() can test only constant values. The if can evaluate relational or logical
expressions.
No two case statements have identical Same conditions may be repeated for number of
W

constants in the same switch. times.


Character constants are automatically Character constants are automatically converted
W

converted to integers. to integers


In switch() case statement, nested if can be In nested if statements switch() case can be used.
used.
LOOPING STATEMENTS:
1. while loop:
 It is a repetitive control structure, used to execute the statements within the body until the
condition becomes false.
 The while loop is an entry controlled loop statement means the condition is evaluated first
and it is true then the body of the loop is executed.
 After executing the body of the loop the condition is once again evaluated and if it is true,
the body is executed once again the process of repeated execution of the body of the loop
until the condition becomes false and the control is transferred out of the loop.
 The body of the loop may have one or more statements the blocking with the braces are
needed only if the body contains two or more statements.
Syntax Example OUTPUT
while(condition) void main() Sum of n Numbers
{ { Enter the Limit Value:10
Body of the loop; int n,i,sum=0;
} clrscr(); Sum = 55
printf("Sum of n Numbers");
printf("\nEnter the Limit Value:");
scanf("%d",&n);
i=0;
while(i<=n)
{
sum=sum+i;
i++;
}
printf("\nSum = %d",sum);

T
getch();
}

E
2. do……while loop:
 The while loop makes a test of condition before the loop is executed.

.N
 In some situations it may be necessary to execute the body of the loop before the test condition
is performed, such a situation the do……while loop is useful.
IA
 It is also repetitive control structure and executes the body of the loop once irrespective of the
condition then it checks the condition and continues the execution until the condition is false.
 Here the statements within the body of the loop are executed once, then it evaluates for the
ND
condition if it is true, then it executes body until the condition becomes false.
Syntax Example OUTPUT
do void main() Sum of n Numbers
NI

{ { Enter the Limit Value:10


Body of the loop; int n,i,sum=0;
}while(condition); clrscr(); Sum = 55
I

printf("Sum of n Numbers");
.K

printf("\nEnter the Limit Value:");


scanf("%d",&n);
W

i=0;
do
{
W

sum=sum+i;
i++;
W

}while(i<=n);
printf("\nSum = %d",sum);
getch();
}

While Do……while
This is the top tested loop. This is the bottom tested loop.
The condition is first tested if the condition is It executes the body once after it checks the
true then the block is executed until the condition condition if it is true the body is executed
becomes false. until the condition becomes false.
Loop will not be executed if the condition is Loop is executed at least once even though
false. the condition is false.

3. for loop:
 The for loop is another repetitive control structure and is used to execute set of instructions
repeatedly until the condition becomes false.
 The assignment incrementation or decrementation and condition checking is done in for
statement only where as other control structures are not offered all these features in one
statement.
For loop has three parts:
1. Initialize counter is used to initialize counter variable.
2. Test condition is used to test the condition.
3. Increment/decrement counter is used to increment or decrement counter variable.
 If there is a single statement within the for loop the blocking with braces is not
necessary if more than one statement includes in body of the loop the statements
within the body must be blocked with braces.
Syntax Example OUTPUT
for(initialize; condition; void main() Sum of n Numbers
increment/ decrement) { Enter the Limit Value:10
{ int n,i,sum=0;

T
Body of the loop; clrscr(); Sum = 55

E
} printf("Sum of n Numbers");
printf("\nEnter the Limit Value:");

.N
scanf("%d",&n);
for(i=0;i<=n;i++)
{
sum=sum+i;
}
IA
printf("\nSum = %d",sum);
ND
getch();
}
NI

4. Nesting of for loops:


 Like if statement for loop also nested. The loop within the loop is called nested loop.
 In nested loops two or more for statements are included in the body of the loop.
I

 The number of iterations in this type of structure will be equal to the number of
.K

iterations in the outer loop multiplied by the number of iterations in the inner loop.
Types of loops:
W

1. Counter controlled loops:


 The counter controlled loops are used in a situation when the programmer knows
in prior exactly how many times the loop will be executed.
W

 These loops are also called as definite repetition loop.


 In this loop the control variable is declared initialized tested and updated regularly
W

for the designed operations.


2. Sentinel controlled loop:
 The sentinel controlled loops are used in a situation when the programmer not
knows in prior exactly the number of times the loop will be executed.
 This loop is also called as indefinite repetition loop, because the no. of repetition
is not known before.
 In this loop the control variable is called sentinel variable it is tested with test
condition for repetition.
Ex:
While(i!=-999)
{
Scanf(“%d”, &i);
Sum = sum+i;
}
Selecting a suitable loop structure:
 Choose either entry-controlled or exit controlled loop depending on the problem.
 Choose either counter-controlled loop or sentinel controlled loop depending on
the problem.
 If the entry-controlled loop is necessary the best suitable loop in while or for.
 If the exit controlled loop is necessary the best suitable loop is do…..while.
 Choose for loop for counter controlled loop and while for sentinel controlled
loops.
UNCONDITIONAL STATEMENTS:
1. break statement:
 It is used to terminate the loop.
 When the keyword break is used inside any ‘C’ loop control automatically transferred to the
first statement after the loop.
 A break is usually associated with an if statement.
 When the break statement is encountered inside a loop the loop is immediately exited and
the program continues with the statement immediately following the loop.

T
Syntax: break;

E
2. continue statement:
 In some situation we want to take the control to the beginning of the loop bypassing the

.N
statements inside the loop which have not yet been executed, for this purpose the continue is
used.
Syntax: continue;
Break IA Continue
Break statement takes the control to the outside Continue statement takes the control to the
ND
of the loop. beginning of the loop.
It is used in switch statement. It is used in loop statements.
Always associated with if condition in loops. This is also associated with if condition.
3. goto statement:
NI

 So far we have seen number of ways of controlling the flow of execution based on the
conditions.
 ‘C’ provides the goto statement to transfer control unconditionally from one place to another
I

place in the program.


.K

 A goto statement can cause program control almost anywhere in the program
unconditionally.
W

 The goto statement requires a label to identify the place to move the execution.
 A label is a valid variable name and must be ended with colon(:).
Syntax:
W

goto label; label:


label: goto label;
W

//Sum of n Numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,sum=0;
clrscr();
printf("Sum of n Numbers");
printf("\nEnter the Limit Value:");
scanf("%d",&n);
for(i=0;i<=n;i++)
sum=sum+i;
printf("\nSum = %d",sum);
getch();
}
OUTPUT:
Sum of n Numbers
Enter the Limit Value:10
Sum = 55

//Sum and average Numbers


#include<stdio.h>
#include<conio.h>
void main()

T
{
int a[10],n,i,sum=0;

E
float avg=0.0;

.N
clrscr();
printf("Sum and average of given Numbers");
printf("\nEnter the Limit Value:");
scanf("%d",&n);
printf("\nEnter the Values:");
for(i=0;i<n;i++)
IA
ND
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
NI

avg=(float)sum/n;
printf("\nSum = %d",sum);
I

printf("\nAverage = %.2f",avg);
.K

getch();
}
OUTPUT:
W

Sum and average of given Numbers


Enter the Limit Value:3
W

Enter the Values:3


6
1
W

Sum = 10
Average = 3.33

//roots of quadratic equation.


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,D;
float Root1,Root2;
clrscr();
printf("Roots of quadratic equation.");
printf("\nEnter the A,B,C Value:");
scanf("%d%d%d",&a,&b,&c);
D=(b*b)-(4*a*c);
if(D>=0)
{
Root1=(float)(-b+sqrt(D))/(2*a);
Root2=(float)(-b-sqrt(D))/(2*a);
printf("\nRoot1 = %.2f",Root1);
printf("\nRoot2 = %.2f",Root2);
}
else
{
printf("\nRoots are imaginary");
}
getch();

T
}
OUTPUT:

E
Roots of quadratic equation.

.N
Enter the A,B,C Value:3
10
2

Root1 = 463.00
Root2 = -466.33
IA
ND
INI
.K
W
W
W
UNIT-3
ARRAYS and STRINGS
Arrays:
 An array is a collection of similar data items, which are stored under a common name.
 Each element of an array is stored in successive locations of the memory.
 Data items can be int, float, char values of data types.
 The elements of the array are known as members of the array.
 Arrays are declared using the symbol square bracket”[ ]” (or) subscript.
Need for Array:
 A single variable store only one value.
 If we want to store more values means we need to declare more variables.
 This problem solved using array.
Types of array:

T
Arrays can be classified into
1. One Dimensional Array

E
2. Two Dimensional Array
3. Multi Dimensional Array

.N
1. One Dimensional Array:
 An array is a collection of similar data items, which are stored under a common name using
single subscript. IA
 One Dimensional Array also called linear array or Single Dimensional Array.
ND
 The array elements must be accessed on an element by element.
 Array accessed by using looping structure(for, while).
 Array elements are always starting at Zero and end with Maximum element-1.
Syntax:
NI

Datatype array_name[size];
Datatype—Type of data items like as int,char,float
Array_name---specifies name of the array
I

Size---element count.
.K

Example: int a[3];


Array index Element values
a[0] 4
W

a[1] 12
a[2] 10
W

Array initialization:
 The array initialized in two ways:
W

1. At compile time
2. At run time
1. At compile time:
o The array elements are initialized at the time of declaration.
Syntax: Datatype array_name[]={list of values};
Example: int marks[3]={45,67,89};
Array index Element values
marks[0] 45
marks [1] 67
marks [2] 89
2. At run time:
o The array elements are initialized at the time of program running.
o The “for” loop is used to initialize values for array element.
Example:
i) Using for loop to initialize value “0” to all the elements.
int a[10],i;
for(i=0;i<10;i++)
a[i]=0;
ii) Using scanf() function to initialize different values.
int a[5],i;
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);
//One Dimensional array Sum and average Numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],n,i,sum=0;
float avg=0.0;
clrscr();
printf("Sum and average of given Numbers");
printf("\nEnter the Limit Value:");
scanf("%d",&n);

T
printf("\nEnter the Values:");
for(i=0;i<n;i++)

E
{
scanf("%d",&a[i]);

.N
sum=sum+a[i];
}
avg=(float)sum/n;
printf("\nSum = %d",sum);
printf("\nAverage = %.2f",avg);
getch();
IA
ND
}
OUTPUT:
Sum and average of given Numbers
Enter the Limit Value:5
NI

Enter the Values:45


2
3
I

10
.K

5
Sum = 65
Average = 13.00
W

2. Two Dimensional array:


o Two dimensional arrays have two subscripts.
W

o We need to store table of values use the 2D array.


o Two pairs of square brackets denoted by rows and columns.
W

Example: A[3][3];
Column-0 Column-1 Column-2
Row-0
Row-1
Row-2

That is represented as
Columns
Column-0 Column-1 Column-2
Rows

Row-0 A[0][0] A[0][1] A[0][2]


Row-1 A[1][0] A[1][1] A[1][2]
Row-2 A[2][0] A[2][1] A[2][2]

Syntax:
Datatype array_name[row_size][column_size];

Initialization:
1. At compile time:
 The values can be initialized at the time of declaration.
Syntax:
Datatype array_name[row_size][column_size]={List of Values};
Example:
A[2][2]={{1,2}{3,4}};
Or
A[2][2]={1,2,3,4};
2. At run time:
 The values can be initialized at the time of running.
 Run time initialization can be do with the scanf() function.
Example:
int a[5][5],I,j;
for(i=0;i<5;i++)
for(j=0;j<5;j++)

T
scanf("%d",&a[i][j]);
Example:

E
//Two Dimensional array or Matrix Multiplication
#include<stdio.h>

.N
#include<conio.h>
void main()
{
int a[2][2],b[2][2],c[2][2],j,i,k;
clrscr();
printf("Matrix Multiplication");
IA
ND
printf("\nEnter the A matrix 4 values:");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
NI

printf("\nEnter the B matrix 4 values:");


for(i=0;i<2;i++)
for(j=0;j<2;j++)
I

scanf("%d",&b[i][j]);
.K

printf("\nResult Matrix:\n");
for(i=0;i<2;i++)
{
W

for(j=0;j<2;j++)
{
W

c[i][j]=0;
for(k=0;k<2;k++)
c[i][j]= c[i][j]+a[i][k]*b[k][j];
W

}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
getch();
}
OUTPUT:
Matrix Multiplication
Enter the A matrix 4 values:1
2
3
4
Enter the B matrix 4 values:5
6
7
8
Result Matrix:
19 22
43 50

//Two Dimensional array or Matrix Addition


#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],b[2][2],c[2][2],j,i;
clrscr();
printf("Matrix Addition");
printf("\nEnter the A matrix 4 values:");

T
for(i=0;i<2;i++)
for(j=0;j<2;j++)

E
scanf("%d",&a[i][j]);
printf("\nEnter the B matrix 4 values:");

.N
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);
printf("\nResult Matrix:\n");
for(i=0;i<2;i++)
{
IA
ND
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
NI

}
printf("\n");
}
I

getch();
.K

}
OUTPUT:
Matrix Addition
W

Enter the A matrix 4 values:3


2
1
W

5
Enter the B matrix 4 values:4
W

6
8
2
Result Matrix:
7 8
9 7

Strings:
 Group of (or) Collection of (or) Array of characters are called strings.
 The strings are specified with pair of double quotes (“ “).
 Where declaring a string it will take null character “\0” at the end of string.
 This null character cannot visible.
Syntax: char array_name[];
Initialization:
 The values of string can be initialized at run time or compile time.
 The string values are initialized at compile time:
Syntax: char array_name[]=”values”;
Example: char name[]=”Senthil”;
 The string values are initialized at run time using scanf():
Syntax:
char array_name[];
scanf(“%s”,array_name);
Example:
char name[];
scanf(“%s”,name);
Reading and Writing:
 Reading & writing the string using scanf() & printf() function through the “%s” control string.
 Also use the gets() and puts() functions.
Syntax:
Read Write
scanf(“%s”,array_name); printf(“%s”,array_name);
gets(array_name); puts(array_name);

T
Example:
char name[15];

E
printf(“Enter the name:”);
scanf(“%s”,name);

.N
printf(“\nName:%s”,name);
OUTPUT:
Enter the name:Senthil
Name:Senthil IA
ND
String Handling (or) Standard Functions:
 The ‘C’ compiler provides the following string handling functions:
S.No. Function Purpose
1. strlen() Find length of the string
2. strcpy() Copy one string to another
NI

3. strcat() Combine two strings


4. strcmp() Comparing two strings
I

5. strrev() Reverse a string


.K

6. strlwr() Convert in to lower case


7. strupr() Convert into upper case
1. strlen():
W

 This function is used to count & return the number of characters present in a string.
Syntax: int var=strlen(string1);
Example:
W

char name[]=”Senthil”;
int len1,len2;
W

len1=strlen(name);
len2=strlen(“Kumar”);
printf(“%s length is %d”,name,len1);
printf(“\n%s length is %d”,”Kumar”,len1);
OUTPUT:
Senthil length is 7
Kumar length is 5
2. strcpy():
 This function is used to copy the contents of one string to another .
Syntax: strcpy(string1,string2);
 The contents of string2 copy to string1.
Example:
char str1[]=”Senthil”,str2[]=”Kumar”;
strcpy(str1,str2);
printf(“String1=%s\nString2=%s”,str1,str2);
OUTPUT:
String1=Kumar
String2=Kumar
3. strcat():
 This function is used to concatenate (or) combine the two strings.
Syntax: strcat(string1,string2);
String2 is combined with string1
Example:
char str1[]=”Senthil”,str2[]=”Kumar”;
strcat(str1,str2);
printf(“The combined string:%s”,str1);
OUTPUT:
The combined string:SenthilKumar

4. strcmp():
 This function is used to compares two strings and find out whether they are same or different.
 The two strings are compared character by character until end of one string is reached.
 When two strings are equal it will give value “Zero” otherwise give any other value.

T
Syntax: int var=strcmp(string1,string2);
Example:

E
char name1[]=”Kalai”,name2[]=”Malai”,name3[]=”Kalai”;
int I,j;

.N
i=strcmp(name1,name2);
j=strcmp(name1,name3);
printf(“Comparison of %s & %s is %d”,name1,name2,i);

OUTPUT:
Comparison of Kalai & Malai is 1
IA
printf(“\nComparison of %s & %s is %d”,name1,name3,j);
ND
Comparison of Kalai & Kalai is 0
5. strrev():
 This function is used to reverse a string.
Syntax: strrev(string1);
NI

Example:
char str1[]=”Senthil”;
strrev(str1);
I

printf(“Reversed String=%s”,str1);
.K

OUTPUT:
lihtneS
W

6. strlwr():
 This function is used to converts the characters of string into lower case characters.
Syntax: strlwr(string1);
W

Example:
char str1[]=”SenThiL”;
strlwr(str1);
W

printf(“Converted lower case:%s”,str1);


OUTPUT:
Converted lower case:senthil
7. strupr():
 This function is used to converts the characters of string into upper case characters.
Syntax: strupr(string1);
Example:
char str1[]=”SenThiL”;
strupr(str1);
printf(“Converted upper case:%s”,str1);
OUTPUT:
Converted upper case:SENTHIL

Sorting & Searching:


Sorting:
 Arrange the elements either in ascending (or) descending order.
 Elements are may be in the form of char, int, float values.
Descending order:
 Bigger number is moved to top of all & smaller number is moved to bottom.
Ascending Order:
 Smaller number is moved to top of all & bigger number is moved to bottom.
Types of Sorting:
1) Bubble sort
2) Insertion sort
3) Selection sort
4) Quick sort
1) Bubble sort:
 It is the one of the easiest sorting method.
 In this method each data item is compared with its neighbor.

E T
.N
IA
ND
I NI
.K

 It like as bubble near with another bubble so that it is called bubble sort.
Diagram:
W
W
W

Example:
//Bubble Sorting
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={35,75,45,5,25},j,i,temp=0;
clrscr();
printf("Bubble Sorting");
printf("\nUnsorted Elements:\n");
for(i=0;i<5;i++)
printf("%d\t",a[i]);
for(i=0;i<5;i++)
for(j=i+1;j<5;j++)
{
if(a[i]>a[j])

T
{
temp=a[i];

E
a[i]=a[j];
a[j]=temp;

.N
}
}
printf("\nSorted Elements:\n");
for(i=0;i<5;i++)
printf("%d\t",a[i]);
getch();
IA
ND
}
OUTPUT:
Bubble Sorting
Unsorted Elements:
NI

35 75 45 5 25
Sorted Elements:
5 25 35 45 75
I

Searching:
.K

 To determine if the particular data item is present in that collection.


 Which data item to find is called the “key”.
 Our task the key element matches in the collection of data items.
W

Types of Search:
1) Sequential (or) Linear search
W

2) Binary search
1) Sequential (or) Linear search:
 It is the search the key element in sequentially.
W

 That is search element matches check with element by element.


 If the searching element is present in at last of the list means it will take more time.
Example:
//Linear or Sequential Search
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={4,21,36,14,62,5,10},key,i,t=0;
clrscr();
printf("Linear or Sequential Search");
printf("\nList of Elements:\n");
for(i=0;i<7;i++)
printf("%d\t",a[i]);
printf("\nEnter the search key:");
scanf("%d",&key);
for(i=0;i<7;i++)

T
{
if(a[i]==key)

E
{
t=1;

.N
printf("\nThe %d is present in %d position",key,i+1);
break;
}
}
if(t==0)
printf("\nThe Element is not present\n");
IA
ND
getch();
}
OUTPUT:
Linear or Sequential Search
NI

List of Elements:
4 21 36 14 62 5 10
Enter the search key:62
I

The 62 is present in 5 position


.K
W
W

UNIT-4
FUNCTIONS:
W

 A function is a set of instructions that are used to perform specified task.


Types of Functions:
i) User defined functions
ii) Built in functions
User Defined Functions:
 The user defined functions has to be written by the programmer.
Built in functions:
 These functions are not required to be written by the programmer.
 Built in functions also called as pre defined (or) library functions.
Need for user defined function:
 The program becomes too large & complex.
 The users cannot go through at glance.
 The task of debugging, testing & maintenance becomes difficult.
Elements of functions:
 The functions contain following three elements:
1) Function declaration
2) Function Definition

E T
.N
3) Function calling
IA
ND
Example:
I NI
.K
W
W
W

1) Function Declaration:
 The function can be declared before they are defined.
 The parameters must match.
Syntax:
Return_type function_name(Parameter list);
Return_type  Datatype of the return value
Function_name  Name of the function
Parameter list  List of parameters
Example:
Int add(int x, int y); or void add();
2) Function Definition:
 The function definition is the actual body of the function.
 It is the process of specifying and establishing the operation.
Syntax:
Return_type function_name(parameter list)
{
Body of the function;
Return data;
}
3) Function call:
 A function can be called by specifying its name, followed by a list of parameters.
 The function definition may return a value to function call.

T
 A semicolon (;) is used at the end of the statement.

E
Syntax:
Function_name(); (or) function_name(parameter);

.N
Value=function_name(parameter);
Example:
Fun(); or fun(a,b);
C=fun(a,b);
IA
ND
Parameters:
 Parameters provide the data communication between the function call & function definition.
 Parameters are also called as arguments.
There are 2 types:
NI

i) Actual parameters
ii) Formal parameters.
Actual and formal parameters must match.
I
.K

i) Actual parameters: These parameters are present in the function call.


ii) Formal parameters: These are present in the function definition.
Example:
W

Void main()
{ void sum(int x, int y)
W

……. {
Body of the function;
W

…… }
Sum(a,b);
…..
……
}
Return Statement:
 Value (or) information is returned from the function definition to the function call.
 A function may contain more than one return statement.
 Return type must be present in definition.
Syntax:
Return; (or) return(value (or) expression);
Example:
int first() int second()
{ {
….. ……
…. …
Return x*x; return a;
} }
Function prototypes:
 The functions are classified into the following types depending on arguments present or not
and the value is returned or not.
 These are called as function prototypes.
a) Function without arguments & no return values
b) Function with arguments & no return vales
c) Function with arguments & with return vales
d) Function without arguments & with return vales

T
a) Function without arguments & no return values:
 Here, there is no data transfer between function call & function definition. i.e.,no

E
arguments

.N
are passed
from main
function & no
IA value is
returned from
the sub
ND
function.
Syntax:
I NI
.K
W
W
W

Example:
void sum();
void main()
{
sum();
}
void sum()
{
int a,b,c;
printf("enter the two values:");
scanf("%d%d",&a,&b);
c=a+b;
printf("sum =%d",c);
}
Output:
enter the two values:10
20
sum =30
b) Function with arguments & no return values:
 In this prototype, data is transferred from function call to the function definition.
 The value does not return the function call so it is called one-way communication.

T
Syntax:

E
.N
IA
ND
INI
.K
W

Example:
void sum(int,int);
W

void main()
{
W

int a,b;
printf("enter the two values:");
scanf("%d%d",&a,&b);
sum(a,b);
}
void sum(int x, int y)
{
int z;
z=x+y;
printf("sum=%d",z);
}
OUTPUT:
enter the two values:10
20
sum =30

c) Function with arguments & with return vales:


 Here, the data is transferred between function call & function definition.
 The value is returned to the function call. So it is called as two way communication.

Syntax:

E T
.N
IA
ND
NI

Example:
void main()
I

{
.K

int a,b,c;
clrscr();
W

printf(“enter the two values:”);


scanf(“%d%d”,&a,&b);
W

c=sum(a,b);
printf(“sum=%d”,c);
getch();
W

}
void sum(int x, int y)
{
int z;
z=x+y;
return z;
}
Output:
Enter the values: 5 10
Sum=15
d) Function without arguments & with return values:
 Here, no data is transferred between function call & function definition.
 But the value is returned from the function definition to the function cal.
 So it is called as one way communication.
Syntax:

E T
.N
Example:
void main()
{
int a,b,c;
clrscr();
IA
ND
c=sum();
printf(“sum=%d”,c);
getch();
NI

}
void sum(int x, int y)
{
I
.K

int x,y,z;
printf(“enter the two values:”);
scanf(“%d%d”,&x,&y);
W

z=x+y;
return z;
W

}
OUTPUT:
W

Enter the values: 5 10


Sum=15

Parameter Passing Methods


There are 2 ways to pass a parameter inside the function. They are:
i) Call by Value
ii) Call by reference

i) Call by Value:
 This method copies the values of actual parameters into the formal parameters of the
function.
 The changes of the formal parameters cannot affect the actual parameters.
 Because formal parameters are photocopy of the actual parameters.

Syntax:
void main()
{
…………
swap(a,b);
……….
}
swap(int a,int b)
{
int temp;
………….
}

T
Example:
void swap1(int,int);

E
void main()

.N
{
int a=10,b=20;
clrscr();
printf("before swap: a=%d\t b=%d",a,b);
swap1(a,b);
IA
ND
printf("\nafter swap: a=%d\t b=%d",a,b);
}
void swap1(int x, int y)
NI

{
int t;
t=x;
I
.K

x=y;
y=t;
printf("\nIn function a=%d\t b=%d",x,y);
W

}
OUTPUT:
W

before swap: a=10 b=20


In function a=20 b=10
W

after swap: a=10 b=20

ii) Call by reference:


 Call by reference is the addresses of actual parameters are copied into the formal parameters
inside the function.
 The address is used to access the actual parameters inside the function also.
 So, Changes made in parameters are permanent.
 Here pointers are used to store the address.
Syntax:
void main()
{
…………..
swap(address of variable);
…………
}
void swap(pointer variable)
{
………..
}

Example:
void swap(int*,int*);
void main()
{
int a=10,b=20;
clrscr();

T
printf("before swap: a=%d\t b=%d",a,b);
swap(&a,&b);

E
printf("\nafter swap: a=%d\t b=%d",a,b);

.N
}
void swap(int *x, int *y)
{
int t;
t=*x;
IA
ND
*x=*y;
*y=t;
}
NI

OUTPUT:
before swap: a=10 b=20
after swap: a=20 b=10
I
.K

Recursion:
 Recursion takes the form of function that calls itself.
W

 A process being performed where one of the instructions is to repeat the process.
 It is similar to looping.
W

 Recursion is the process of calling the same function itself again and again until some
condition is satisfied.
W

Syntax:
void function1();
{
---
---
function1();
}

 The above function function1() is called themselves continuously.


Example:
void main()
{
int n,f;
printf("Enter the Number:");
scanf("%d",&n);
printf("\nThe factorial of %d = %d",n,fact(n));
}
int fact(int x)
{
int f;
if(x==1)
return 1;
else
f=x*fact(x-1);
return f;
}

T
OUTPUT:
Enter the Number:5

E
The factorial of 5 = 120

.N
IA
ND
I NI
.K
W
W
W

Tower of Hanoi:
 The Tower of Hanoi is a mathematical game or puzzle.
 It consists of three rods, and a number of disks of different
sizes which can slide onto any rod.
 The puzzle starts with the disks in a neat stack in ascending
order of size on one rod, the smallest at the top, thus making a
conical shape.
The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the
stacks and placing it on top of another stack i.e. a disk can only
be moved if it is the uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.

ENGG
With three disks, the puzzle can be solved in seven moves. The minimum number of moves
required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks.

T
The Standard Library Functions
 Some of the "commands" in C are not really "commands" at all but are functions.

E
 For example, we have been using printf and scanf to do input and output, and we have used

.N
rand to generate random numbers - all three are functions.
 There are a great many standard functions that are included with C compilers and while these
are not really part of the language, in the sense that you can re-write them if you really want
IA
to, most C programmers think of them as fixtures and fittings.
 ASCII(American Standard Code for Information Interchange)
 The most useful functions they contain follows:
ND
S.No. Function Meaning Example OUTPUT
Mathematics functions
NI

1. sqrt() It evaluates square root of x x=25; sqrt(x); 5


2. abs() The absolute value of integer quantity x=-75; abs(x); 75
3. pow(x,y) It evaluates the values of xy x=3,y=2; pow(x,y); 9
I

4. ceil() Round of given number. x=5.6;ceil(x); 6


.K

Trigonometric Functions
5. sin() It evaluates sine value. x=30; sin(x); -0.99
W

6. cos() It evaluates cosine value. x=30; cos(x); 0.15


7. tan() It evaluates tangent value. x=30; tan(x); -6.41
W

Character Function
8. toascii() It gives ASCII value of the character. x=’a’; ascii(x); 97
9. tolower() It converts lowercase character. x=’A’; tolower(x); a
W

10. toupper() It converts uppercase character. x=’a’; toupper(x); A

Example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<ctype.h>
void main()
{
int x,y=2;
printf("\nEnter the number:");
scanf("%d",&x);
printf("\nThe squareroot of %d is %f",x,sqrt(x));
printf("\nThe value of %d power%dis%f ",x,y,pow(6,2));
printf("\nThe ceiling of 6.7 is %f",ceil(6.7));
printf("\nThe floor of 6.7 is %f",floor(6.7));
printf("\nThe absolute value of -6 is %d",abs(-6));
printf("\nThe value of sin 45 is %f",sin(45));
printf("\nThe uppercase of 'a' is %c",toupper('a'));
printf("\nThe uppercase of 97 is %c",toupper(97));
getch();
}
OUTPUT:
Enter the number:6
The squareroot of 6 is 2.449490
The value of 6 power 2 is 36.000000

T
The ceiling of 6.7 is 7.000000
The floor of 6.7 is 6.000000

E
The absolute value of -6 is 6

.N
The value of sin 45 is 0.850904
The uppercase of 'a' is A
The uppercase of 97 is A
IA
ND
Pointers:
 A pointer is a variable that is used to store the address of another variable.
 It is declared like other variables and also it is always denoted by asterisk “*” operator.
 Each variable has two attributes:
NI

o Address
o Value
I

 It can be used to access and manipulate data stored in the


.K

memory.
 Ordinary Variable:
int a=5;
W

aaccess the value


&a access the address of variable.
W

a variable
5 value
W

4002 address
Syntax: Data_type *pointer_variable;
Example: int *p;

Advantages:
1. It is increase the speed of execution.
2. It is saving memory space.
3. It enables us to access the memory directly.
4. It is also provide an alternate way to access an array.
5. Multiple data items can receive in the function.
Initializing pointer:
 The process of assigning the address of a variable to a pointer variable is called initialization.
 The location of the variable in system memory.
 This can be achieved through the ampersand(&) symbol.
 The ampersand(&) symbol is an address operator.
 It takes the address of the variable.
 Pointers must be initializing with assigning address of the variable.
Example:
void main()
{
int a=10,*p;
p=&a;
printf("\n*p=%d\tp=%d\t&p=%d\t&a=%d",*p,p,&p,&a);
}
OUTPUT:
*p=10 p=-12 &p=-14 &a=-12
 *pvalue of the address stored in pointer variable.
 Paddress of the variable.

T
 &paddress of the pointer variable.

E
 &aaddress of the variable.
a variable *p

.N
10 value -12
-12 address -14

Pointer Arithmetic:
 C pointer is an address, which is a numeric value.
IA
ND
 Therefore, you can perform arithmetic operations on a pointer just as you can a numeric value.
 There are four arithmetic operators that can be used on pointers: ++, --, +, and -
Data type Initial Address operation address after operation bytes of data type
NI

char 4000 ++ 4001 1


char 4000 -- 3999 1
int 4000 ++ 4002 2
I

int 4000 -- 3998 2


.K

float 4000 ++ 4004 4


float 4000 -- 3996 4
W

Incrementing a Pointer
 Incrementing pointer is generally used in array.
W

 The variable pointer to access each succeeding element of the array.


 Incrementing pointer variable depends upon datatype of the pointer variable.
W

Example:
void main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
ptr = var;
for ( i = 0; i < 3; i++)
{
printf("\nAddress of var[%d] = %u", i, ptr );
printf("\nValue of var[%d] = %d", i, *ptr );
ptr++;
}
}
OUTPUT:
Address of var[0] = 65520
Value of var[0] = 10
Address of var[1] = 65522
Value of var[1] = 100
Address of var[2] = 65524
Value of var[2] = 200

Decrementing a Pointer
 The same considerations apply to decrementing a pointer, which decreases its value by the
number of bytes of its data type as shown below:
Example:
void main ()

T
{
int var[] = {10, 100, 200};

E
int i, *ptr;

.N
ptr = &var[3-1];
for ( i = 3; i > 0; i--)
{
printf("Address of var[%d] = %u\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
IA
ND
ptr--;
}
}
NI

OUTPUT:
Address of var[3] = 65524
Value of var[3] = 200
I

Address of var[2] = 65522


.K

Value of var[2] = 100


Address of var[1] = 65520
W

Value of var[1] = 10
W

Pointers and Arrays or Pointers and Functions:


• The elements of the array can also be accessed through a pointer.
• Pointers also send the array to functions.
W

Syntax:
Pointer_variable=array_name;
Example:
void fun(int[]);
void main()
{
int a[3]={10,20,30},*p;
p=a;
fun(p);
}
void fun(int b[])
{
int i,total=0;
for(i=0;i<3;i++)
total=total+b[i];
printf("\nTotal=%d",total);
}
OUTPUT:
Total=60

E T
.N
Structures:
IA
Unit-5
Structures and Union
ND
 Structure is a compound datatype.
 It stores different type of data items.
 It is used to store dissimilar data items.
 Structure is creating with the “struct” keyword.
NI

 It is the one of the storage unit.


 Different type of data items can be store in different memory space.
I

 The elements of structure are called members.


.K

 It must be declare and defined.


W

INT FLOAT
W

Structures
W

CHAR DOUBLE

Structure Declaration and Definition:


 It must be declare and defined.
 Structure is creating with the “struct” keyword.
 Structure finished declaration with semicolon(;).
 Accessing members with dot(.) operator.
Syntax:
struct structure_name
{
Datatype variables;
----
};
Creating structure Variable:
struct structure_name structure_variable;
Accessing structure Member:
structure_variable.member;

Difference between structure and array:


S.No. Array Structure
1. It is a collection of similar data items. it is collection of dissimilar data items
2. It is derived data type. It is a user defined data type.
3. It behaves like a built-in data types. It must be declared and defined.
4. An array can be increase or decrease. Its members can be added.

Example:
//Student Details using Structure
struct stud
{

T
int regno,m1,m2,m3,total;

E
char name[20],result[5];
};

.N
void main()
{
struct stud s1,s2;
printf("\nStructures");
printf("\nEnter the Regno, Name:");
scanf("%d%s",&s1.regno,s1.name);
IA
ND
printf("\nEnter the Mark1, Mark2, Mark3:");
scanf("%d%d%d",&s1.m1,&s1.m2,&s1.m3);
s1.total=s1.m1+s1.m2+s1.m3;
NI

if(s1.m1<50||s1.m2<50||s1.m3<50)
strcpy(s1.result,"Fail");
else
I

strcpy(s1.result,"Pass");
.K

s2=s1; //Assigning structure


printf("Regno\tName\tMark1\tMark2\tMark3\tTotal\tResult\n");
printf("%d\t%s\t%d\t%d\t%d\t%d\t%s",s1.regno,s1.name,s1.m1,s1.m2,s1.m3,s1.total,s1.result);
W

printf("\nStructure--2");
printf("\nRegno\tName\tMark1\tMark2\tMark3\tTotal\tResult\n");
W

printf("%d\t%s\t%d\t%d\t%d\t%d\t%s",s2.regno,s2.name,s2.m1,s2.m2,s2.m3,s2.total,s2.result);
getch();
}
W

OUTPUT:
Enter the Regno, Name:345
kumar
Enter the Mark1, Mark2, Mark3:67
78
61
Regno Name Mark1 Mark2 Mark3 Total Result
345 kumar 67 78 61 206 Pass
Structure--2
Regno Name Mark1 Mark2 Mark3 Total Result
345 kumar 67 78 61 206 Pass

Structure within structure:


 A structure can be declared within another structure.
 It is also called nesting of structure.
 The structure variables can be normal variable or pointer variable.
 Nesting of more than one type of structure is allowed.
 Structure cannot be nested within itself.
Syntax:
struct struct_1
{
----
----
};
struct struct_2
{
----
----
struct struct_1 s1;
};

T
Example:

E
// Structure within structure
struct college_detail

.N
{
int college_id;
char college_name[20];
};
struct student_detail
{
IA
ND
int regno;
char name[20];
float percent;
struct college_detail c1;
NI

};
void main()
I

{
.K

struct student_detail s1={703,"kumar",87.3,1300,"XYZ college"};


printf("\nStructures within Structure\n");
printf("Regno\tName\tpercentage\tCollege ID\tCollege Name\n");
W

printf("%d\t%s\t%f\t%d\t%s",s1.regno,s1.name,s1.percent,s1.c1.college_id,s1.c1.college_name);
getch();
W

}
OUTPUT:
Structures within Structure
W

Regno Name percentage College ID College Name


703 kumar 87.300003 1300 XYZ college

Example:
//Employee Details using Structure
void dummy(float *a)
{
float b=*a; //perform some floating access
dummy (&b); //calling a floating point function
}
struct employee1
{
int empno;
char name[10];
float salary;
};
void main()
{
struct employee1 e[10];
int i,n;
printf("\nEnter the no.of Employees:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the employee empno,name,salary:");
scanf("%d%s%f",&e[i].empno,e[i].name,&e[i].salary);
}
printf("\nEmployee Details\n");
printf("\nEMPNO\tNAME\tSALARY");
for(i=0;i<n;i++)

T
printf("\n%d\t%s\t%.2f",e[i].empno,e[i].name,e[i].salary);
getch();

E
}

.N
OUTPUT:
Enter the no.of Employees:2
Enter the employee empno,name,salary:23
Raj
5000
Enter the employee empno,name,salary:24
IA
ND
Kumar
3500
Employee Details
EMPNO NAME SALARY
NI

23 Raj 5000.00
24 Kumar 3500.00
I
.K

Union
• A Union is a collection of different data items, which are stored under a common name.
• Here same memory is shared by its members.
W

• The keyword union is used to define a union.


• Size of union is equal to the size of largest member.
W

• Memory allocated is shared by individual members of union.


• The address is same for all the members of a union.
• Altering the value of any of the member will alter other member values.
W

• Only one member can be accessed at a time.


• Only the first member of a union can be initialized.

Syntax:
union union_name
{
union element1;
union element2;
…………………
};
Example:
union result
{
int mark;
float avg;
char grade;
};
union result s;

T
Structure Union
1.The keyword struct is used to define a structure 1. The keyword union is used to define a union.

E
2. The size of structure is greater than or equal to the 2. Size of union is equal to the size of largest

.N
sum of sizes of its members. member.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.
4. The address of each member will be in ascending
order.
5 Altering the value of a member will not affect
IA
4. The address is same for all the members of a
union.
5. Altering the value of any of the member will
ND
other members of the structure. alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at 7. Only the first member of a union can be
NI

once. initialized.

Example:
I

void dummy(float *a)


.K

{
float b=*a; //perform some floating access
W

dummy (&b); //calling a floating point function


}
union employee1
W

{
int empno;
char name[10];
W

float salary;
};
void main()
{
union employee1 e[10];
int i,n;
printf("\nEnter the no.of Employees:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the employee empno,name,salary:");
scanf("%d%s%f",&e[i].empno,e[i].name,&e[i].salary);
}
printf("\nEmployee Details\n");
printf("\nEMPNO\tNAME\tSALARY");
for(i=0;i<n;i++)
printf("\n%d\t%s\t%.2f",e[i].empno,e[i].name,e[i].salary);
getch();
}
OUTPUT:
Enter the no.of Employees:2
Enter the employee empno,name,salary:23
Raj
5000
Enter the employee empno,name,salary:24
Kumar
3500
Employee Details
EMPNO NAME SALARY
16384 5000.00

T
-16384 3500.00

E
Preprocessor:
 It is a program that processes the source program before compilation.

.N
 The C preprocessor executes before a program is compiled.
 Preprocessor directives begin with # and only white-space characters and comments may
IA
appear before a preprocessor directive on a line.
 It operates under the following directives
ND
1. File Inclusion
2. Macro substitution
3. Conditional inclusion
NI

File Inclusion:
• It is used to include some file that contains functions or some definitions.
• Copy of a specified file included in place of the directive
I
.K

Syntax:
#include<filename> Searches standard library for file
(or) #include“filename” Searches for user-defined files
W

Example:
#include<stdio.h>
W

#include<conio.h>
#include "addition.txt"
void main()
W

{
int a,b;
printf("\nEnter the numbers:");
scanf("%d%d",&a,&b);
printf("The Value is %d",add(a,b));
getch();
}
addition.txt
int add(int a,int b)
{
return(a+b);
}
OUTPUT:
Enter the numbers:7
4
The Value is 11
Macro Substitution:
• It is used to define and use integer, string, or identifier in the source program
• The three forms of macros are
– Simple Macro
– Argumented Macro
– Nested Macro
1) Simple Macro:
 It is used to define some constants.
Syntax
#define identifier string/integer
Example:
#include<stdio.h>
#include<conio.h>
#define pi 3.14

T
#define CITY "chennai"
void main()

E
{

.N
printf("The Value is %f",2*pi);
printf("\nThe Value CITY is %s",CITY);
getch();
}
OUTPUT:
The Value is 6.280000
IA
ND
The Value CITY is chennai

2) Argumented Macro
• It is used to define some complex forms in the source program.
NI

Syntax:
#define identifier (v1,v2,….) string/integer
I

Example:
.K

#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
W

void main()
{
W

printf("The Value of 3 cube is %d",cube(3));


getch();
}
W

OUTPUT:
The Value of 3 cube is 27
3) Nested Macro
 Here one macro is used by another macro.
Example:
#include<stdio.h>
#include<conio.h>
#define a 3
#define sq a*a
void main()
{
printf("The Value is %d",sq);
getch();
}
Output:
The Value is 9
Conditional Inclusion:
 It is used to include some conditional statements.
Example:
#include<stdio.h>
#include<conio.h>
#define a 3
#ifdef a
#define c a+5
#endif
void main()
{
printf("\nThe value C is %d",c);
getch();
}

T
Output:

E
The value C is 8

.N
IA
ND
I NI
.K
W
W
W

S-ar putea să vă placă și