You are on page 1of 152

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

UNIT I
INTRODUCTION
Generation and Classification of Computers- Basic Organization of a Computer Number
System Binary Decimal Conversion Problems. Need for logical analysis and thinking
Algorithm Pseudo code Flow Chart.

Introduction:
A Computer is an electronic machine that accepts data from the user, process the data by
performing calculations and operations and generate the desired output results.

Digital and Analog Computers:

A digital computer uses distinct values (0s and 1s) to represent the data. The computers
that we use at our homes and offices are digital computers.

Analog Computer that represents data as variable across a continuous range of values.
Analog computers are used for measuring parameters that vary continuously in real time
such as temperature.

Characteristics of computer:
Speed:
The computer process the data extremely fast, at the rate of millions of
instructions execute per second.
A computer can perform a huge task in few sec where a human being may take
hours or even days to complete the same task.
Accuracy:
The degree of accuracy of computer is very high and every calculation is
performed with the same accuracy.
For example, the computer can accurately give the result of division of any two
numbers up to 10 decimal places.
Diligence or Endurance:

When used for a longer period of time, the computer does not get tired or fatigued.
Page 1

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

It can perform long and complex calculations with the same speed and accuracy.

Versatility:

It means the capacity to perform completely different type of work.


For example: At a moment a computer can be used to draft a letter. Next moment it
can be used print a document or play a music file etc.,
Computers plays a major role in all fields such as space exploration, whether
forecasting, research, Teaching, Railways, industry and Banking etc.

Storage Capability:

Computers are capable of storing huge amount of data and it can be located and
retrieved very quickly.
It uses storage devices such as hard disk to store huge amount of data.

Limitations of a computer:

Computer can only perform tasks that it has been programmed to do.
Computer cannot do any work without instructions from the user.
It executes instructions as specified by the user and does not take its own decision.

History of Computer:
Until the development of the first generation computers based on vacuum tubes, there had been
several developments in the computing technology related to the mechanical computing devices.
1. Calculating machines:
ABACUS were the first mechanical calculating device for counting of large numbers.
The word ABACUS means calculating board.
It consists of bars in horizontal positions on which sets of beads are inserted.
The horizontal bars have 10 beads each, representing units, tens, hundreds, etc.

Page 2

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

2. Napiers Bones was a mechanical device built for the purpose of multiplication in
1617 AD by an English mathematician John Napier.

3. Slide Rule
Slide rule was developed by an English mathematician Edmund Gunter in the
16the century.
Using the slide rule, one could perform operations like addition, subtraction,
multiplication and division.
It was used extensively till late 1970s.

4. Pascals adding and subtraction machine was developed by Blaise Pascal. It could add and
subtract. The machine consisted of wheels, gears and cylinders.

Page 3

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

5. Leibnizs multiplication and Dividing machine was a mechanical device that could both
multiply and divide. The German philosopher and mathematician Gottfried Leibnizs built it
around 1673.

6. Punch Card system was developed by Jacquard to control the power loom in 1801. He
invented the punched card reader that could recognize the presence of hole in the punched card
as binary one and the absence of the hole as binary zero. The 0s and 1s are the basis of the
modern digital computer.

Page 4

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

7. Babbages analytical Engine an Englishman Charles Babbage built a mechanical machine


to do complex mathematical calculations, in the year 1823.The machine was called as difference
engine.
Later, Charles Babbage and Lady Ada Lovelace developed a general purpose calculating
machine, the analytical engine. Charles Babbage is also called the father of computer.

8. Holleriths punched card tabulating machine was invented by Herman Hollerith. The
machine could read the information from a punched card and process it electronically.
Page 5

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Generations of Computers:
Each generation of computer is designed based on a new technological development,
resulting in better, cheaper and smaller computers that are more powerful, faster and
efficient than the previous generation computers.
Currently there are five generation of computer.
First Generation Computers (1940 to 1956):
Hardware technology:
These computers used vacuum tube for circuitry and magnetic drums for memory.
Input devices: punched cards and paper tapes.
Output devices: printouts
Software Technology:
Instructions were written in machine language used 0s and 1s.
These computers could solve one problem at a time.
Computing Speed:
The computation time was in milli seconds.( 1 milli second = 1X10-3 second)
Physical appearance:
The computers were enormous in size and required a large room for installation.
Application:
They were used for scientific applications such as computing device.
Example:
UNIVA( Universal automatic computer,
ENIAC (Electronic numerical integrator and calculator)
EDVAC (Electronic discrete variable automatic computer)

Page 6

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

The first generation computers used a large number of vacuum tubes and it generated a
lot of heat and it consumes more electricity.
Since these computers used machine language, it was difficult to understand by the
human.

Second Generation Computers (1956 to 1963):


Hardware technology:
These computers used transistors for circuitry and magnetic core technology for primary
memory and magnetic tapes, magnetic disks for secondary memory.
Input devices: input still through punched cards and paper tapes.
Output devices: printouts
Software Technology:
Instructions were written in Assembly language uses mnemonics like ADD, SUB etc.
Early version of high level language like COBOL and FORTRAN were also developed.
Computing Speed:
The computation time was in micro seconds.( 1 micro second = 1X10-6 second)
Physical appearance:
Transistors are small in size than vacuum tubes, thus size of the computer was very much
reduced.
Application:
They were used for commercial application.
Example:
PDP-8, IBM 1401 and CDC 1604
Since these computers used assembly language, it was easier than machine language.
But these computers need assembler for converting the assembly language into machine
language.

Page 7

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Third Generation Computers(1964 to 1971):


Hardware technology:
These computers used Integrated circuits (IC). In an IC chip, multiple transistors are
placed on a silicon chip.
Input devices: keyboard, mouse and many input devices invented here.
Output devices: monitor, printer and many
Software Technology:
Instructions were written in high level language such as C, C++, and Java etc.
Operating system also introduced in this generation for easy interaction to the computer
and for multiprocessing.
Computing Speed:
The computation time was in nano seconds.( 1 nano second = 1X10-9 second)
Physical appearance:
ICs are very small in size, thus size of computer also small.
Application:
They were used for all kind of applications from business to research.
Example:
IBM 370, PDP 11.
Since this computer using high level language, it is very easy for human.
But these computers need compiler for converting the high level language into machine
language.

Fourth Generation Computers (1971 to present):


Hardware technology:
They use the Large Scale Integration (LSI) and Very Large Scale Integration (VLSI)
Technology.
In this VLSI technology hundreds of thousands of components to be integrated in a small
chip. This is called microprocessor.
Page 8

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Semi conductor memory (RAM and ROM), Hard disk, CD are using for memory.
Input devices: keyboard, mouse and all present input devices.
Output devices: Monitor printer and all present output devices.
Software Technology:
All the present high level languages (C, C++, Java, C#, .Net etc) are the gift of this
generation.
Several new operating systems like MS DOS, MS-WINDOWS developed and also GUI
interface.
Computing Speed:
The computation time was in pico seconds.( 1 pico second = 1X10-12 second)
Physical appearance:
Microprocessors are very small in size, even now days computers are in the size of palm.
Application:
It covers all areas such as personal use, business, space craft, railways and research etc.
Example:
Intel 4004 was the first microprocessor. Now dual core processor etc.
These computers need advanced compiler for converting the high level language into
machine language.

Fifth Generation Computer: (present to future)

This generation use Super Large Scale Integrated (SLSI) chip that are able to store
millions of components on a single chip.
It requires large memory and speed is extremely high.
The fifth generation computers are based on Artificial Intelligence (AI). They try to
simulate the human way of thinking and reasoning.
Example: Expert System (ES), Natural Language Processing (NLP) , Speech recognition,
voice recognition , robotics etc.
This generation of computer uses parallel processing that allows several instructions to be
executes in parallel, instead f serial execution. The Intel dual core microprocessor uses
parallel processing.
Page 9

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

It is still in a developmental stage

Comparison: generation of computers

Classification of computers:
The computers are broadly classified into four categories based on their sizes and type:
(1)
(2)
(3)
(4)

Microcomputers
Minicomputers
Mainframe computers
Super computers

Microcomputers:
Microcomputers are small, low cost and single user digital computer.
Input, output and CPU are on a single IC chip.
Page 10

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

It is mainly used in offices, homes, schools, shops etc.


1. Desktop computer:
It is a standalone machine that can be placed on the desk.
Externally, it consists of keyboard and monitor, and the system unit
containing the CPU, memory and hard disk drive etc.
It is not very expensive and is suited to the needs of a single user at home,
small business and organizations.
Ex: Apple, Del and Lenovo
2. Notebook computer:
They are portable and have all the features of a desktop computer.
The advantage of the laptop is that it is small in size and it can be carried
anywhere, has a battery backup.
Laptops can be costlier than the desktop machines.
3.Netbook:
These are smaller notebooks optimized for low weight and low cost and
are designed for accessing web applications.
Netbooks are used for streaming videos or music, emailing, web surfing or
instant messaging.
The word netbook was created as a blend of Internet and notebook.
4. Tablet computer:
It has all the features of notebook computer but it can accept input from a
stylus or a pen instead of the keyboard.
It has a touch screen instead of mouse.
5. Smart Phones:
Smart phones are cellular phones that function both as a phone and as a
small PC.
They may use a stylus or a pen, or may have a small keyboard.
They can be connected to the internet wireless.
Blackberry, Apple, HTC, Nokia and LG are some of the manufacturers of
smart phones.
6. Handheld computer or Personal digital assistant(PDA):
It is a small computer that can be held on the top of the palm.
PDA uses a pen or stylus for input.
PDAs do not have a disk drive and thus they have a limited amount of
memory.
They can be connected to the internet via wireless communication.
Casio and Apple are some of its manufacturers.
Mini Computer:
Page 11

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Minicomputers are mainly multiprocessors and multi user systems where many
users simultaneously work on the systems. It supports 4-200 users simultaneously.
They have high processing speed and high storage capacity than the micro
computers.
The users can access the minicomputer through their PCs or terminal.
They are used for real time applications in industries, research centers, etc.
PDP 11, IBM 8000 series are some of the widely used mini computers.
Mainframe Computer:
Mainframe computers are large and powerful systems generally used in
centralized databases. These are used to handle huge volumes of data.
These are multi-user and multi-programming and high performance computers.
The user accesses the mainframe computer via a terminal that may be a dumb
terminal.
Highly sophisticated operating systems are needed to control and supervise their
operations.
It is used in research organizations, large industries, large business and
government sectors, banks and ticket reservations etc.
Example: CDC 6600 and IBM ES000 series.
Super Computer:
Super computer is the most powerful of all computers. They are the fastest and
most expensive machines.
Super computers are built by interconnecting thousands of processors that can
work in parallel.
Speed, accuracy, memory capacity higher than all other computers.
It can perform billions of instructions per second ( 1 super computer = 40,000
micro comp)
Weather forecasting, space research, weapons research, atomic research etc are
some of the applications
.Example: IBM Roadrunner, IBM Blue gene and Intel ASCI red.

Basic Organization of a computer:


Computer is an electronic device that accepts data as input, processes the input data by
performing mathematical and logical operations on it and gives the desired output. The computer
system consists of 4 parts :
(1) Hardware
(2) Software
Page 12

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

(3) Data
(4) Users
(1) Hardware:
Hardware consists of the mechanical parts that make up the computer as a
machine.
The devices are required for input, output, storage and processing of the data.
Keyboard, monitor, hard disk, printer, processor and motherboard are some of the
hardware devices.
(2) Software:
Software is the set of instructions that tells the computer about the tasks to be
performed and how these tasks are to be performed.
Program is a set of instructions, written in a language understood by the
computer, to perform specific tasks.
A set of programs and documents are collectively called as software.
(3) Data:
Data are isolated values or raw facts. The data is provided as input to the
computer, which is processed to generate some meaningful information.
(4) Users:
Users are people who write computer programs or interact with the computer.
Programmers, data entry operators, system analysts and computer hardware
engineers fall into this category.
The Input-Process-Output Concept:
A computer is an electronic device that 1) Accepts data, 2) Processes data, 3) Generates output
and 4) stores data. The concept of generating output information from the input data is referred
to as input-process-output concept.
(1) Input : The computer accepts input data from the user via an input device like keyboard.
The input data can be characters, word, text, sound, images, document etc.
(2) Process : The computer processes the input data. For this, it performs some actions on the
data by using the instructions given by the user of the data. The action could be an
arithmetic or logic calculation, editing, modifying a document etc. During processing the
data, instructions and the output are stored temporarily in the computers main memory.

Page 13

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

(3) Output : Output is the result generated after processing of data. The output may be in the
form of text, sound, image, document etc. The computer may display the output on a
monitor, send output to the printer for printing, play the output etc.
(4) Storage : The input data, instructions and output are stored permanently in the secondary
storage devices like tape or disk. The stored data can be retrieved later, whenever needed.

Components of computer hardware:


The computer system hardware consists of three main components:
(1) Input / Output unit (I/O) unit
(2) Central processing Unit (CPU)
(3) Memory unit.
I/O unit consists of the Input unit and the output unit. CPU performs calculations and
processing on the input data to generate the output. The Memory unit is used to store the
data, the instructions and the output information.
(1)Input/Output unit:
The user interacts with the computer via the I/O unit. The input unit accepts data from the
user and the output unit provides the processed data i.e. the information to the user.
The input unit converts the data that it accepts from the user, into a form that is
understandable by the computer.
Similarly the output unit provides the output in a form that is understandable by the user.
The input is provided to the computer using input devices like keyboard, trackball and
mouse.
Some of the commonly used output devices are monitor and printer.
(2)Central processing Unit:
CPU controls, coordinates and supervises the operations of a computer.
CPU is called as the brain of the computer.
It is responsible for processing of the input data. CPU consists of Arithmetic Logic
Unit(ALU) and Control Unit(CU).
CPU has a set of registers for temporary storage of data, instructions, addresses and
intermediate results of calculation.
The CPU is fabricated as a single Integrated Circuit(IC) chip and is also known as the
microprocessor.
CPU executes the stored program instructions, i.e. instructions and data are stored in
memory before execution.
Page 14

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

It interprets the program instructions and performs the arithmetic and logic operations
required for processing of data. Then it sends the processed data or result to the memory.
(a)Arithmetic Logic Unit:
ALU consists of two units Arithmetic unit and Logic unit.
The arithmetic unit performs arithmetic operations on the dat. Some of the
arithmetic operations supported by the arithmetic unit are addition, subtraction,
multiplication and division.
The Logic unit of ALU is responsible for performing logic operations. Logic unit
performs comparisons of numbers, letters and special characters. Logic operations
include testing for greater than, less than or equal to condition.
ALU performs arithmetic and logic operations, and uses registers to hold tha data
that is being processed.
(b)Registers:
Registers store data, instructions, addresses and intermediate results of processing.
Registers are often referred as CPSs working memory.
The data and instructions that require processing must be brought in the registers
of CPU before they a can be processed. For example, if two numbers are to be
added, both numbers are brought in the registers, added and the result is also
placed in a register.
Registers are used for different purposes, with each register serving a specific
purpose. Some of the important registers in CPU are as follows:
Accumulator(ACC) Stores the result of the arithmetic and logic operations.
Instruction Register(IR) contains the current instruction most recently fetched.
Program counter (PC) contains the address of next instruction to be processed.
Memory Address Register(MAR) contains the address of next location in the
memory to be accessed.
Memory Buffer Register (MBR) temporarily stores data from memory or the
data to be sent to memory.
Data Register (DR) stores the operands and any other data.
(c)Control Unit:
Control unit organizes the processing of data and instructions. It acts as a
supervisor and controls and coordinates the activity of the other units of
computer.
CU tells when to fetch the data and instructions, what to do, where to store the
results, the sequencing of events during processing etc.
CU holds the CPUs instruction set, which is a list of all operations that the CPU
can perform.
(3)Memory unit:
Page 15

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

The memory unit consists of cache memory and primary memory.


Primary memory or main memory is used to store the data and instructions during
execution of the instruction.
Random Access Memory(RAM) and Read Only Memory(ROM) are the primary
memory.
There is another kind of storage unit is referred as the secondary memory. Secondary
storage is non-volatile and is used for permanent storage of data and programs. Magnetic
disks, Optical disks and magnetic tapes are examples of secondary storage.
(a) Cache memory:
Cache memory is a very high speed memory placed in between RAM and CPU.
Cache memory increases the speed of processing.
Cache memory is storage buffer that stores the data that is used more often,
temporarily and makes them available to the CPU at a faster rate.
(b) Primary Memory:
Primary memory is the main memory of the computer.
It is used to store data and instruction during the processing of data.
Primary memory is of 2 types: Random Access Memory (RAM) and Read Only
Memory (ROM).
RAM is volatile. It stores data when the computer is turned on. The information
stored in RAM gets erased when the computer turned off.
ROM is non-volatile. The storage in ROM is permanent in nature.
(c)Secondary Memory:

Secondary memory stores data and instructions permanently.


It provides back-up storage for data and instructions.
It has a high storage capacity than the primary memory.
It is also cheaper than the primary memory.
It takes longer time to access the data and instructions stored in secondary
memory than in primary memory.

Number systems:
A number is required for counting or to express the amount of some quantity. It consists of a
group of symbols called digits, which are arranged in a definite manner.
The most widely adopted system is the decimal number system which has ten digits (0, 1, 2
9), the octal system has eight digits (0, 1, 2, ..7), the hexadecimal system has sixteen digits (0,
1 9, A, B, C, D, E, F) and the binary system has only two (0 & 1).

The number systems are basically of two types:


Page 16

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

1. Non positional number system


2. Positional number system
1. Non positional number system:
The non positional number system with which all of us are familiar is the Roman number
system.

This number system is difficult to use as it has no symbol for zero.

2. Positional number system:

The most widely used number system is the positional number system.

In this system the position of a digit indicates the significance to be attached to that digit.

For e.g.: 3977


7 * 100 -> Unit Position
7 * 101 -> Tenth Position
9 * 102 -> 100th Position
3 * 103 -> 1000th Position

BINARY NUMBER SYSTEM:


Almost all digital computers are based on binary number system
Binary means two, the binary system uses only two digits i.e. 0s and 1s.
The base or radix of binary number system is (2) because it contains only two
numbers.
The weight assigned to bits in this system is power of 2.

24

23

22

21

20

2-1

2-2

2-3

2-4

DECIMAL NUMBER SYSTEM:


The number system that is most commonly used is the decimal number system.
In this number system the base or radix is 10 and there are altogether ten number
i.e. 0,1,2,3,4,5,6,7,8,9.
In the decimal number system, the successive position to the left of the decimal
point represents units, tens, hundreds, thousands, etc.
Example:

Page 17

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

In decimal number system 258.34 10 or 258.34 consists the digits


4 in the position

(4 * 10-2)

3 in the position

(3 * 10-1)

8 in the unit position

(8 * 100)

5 in the tenth position

(5 * 101)

2 in the hundred position

(2 * 102)

and its values can be written as


2 * 102 + 5 * 101 + 8 * 100 . 3 * 10-1
2 * 100 + 5 * 10 + 8 * 1
200 +

50 + 8

+ 4 * 10-2
. 3 * 1 / 10 + 4 * 1 / 100
. 0.3

+ 0.04

(258.34)10 = 258.34
OCTAL NUMBER SYSTEM:
The number system with base or radix (8) is known as octal number system. There are
only eight digits i.e. 0, 1,2,3,4,5,6,7.

84

83

82

81

80

8-1

8-2

8-3

8-4

HEXADECIMAL NUMBER SYSTEM:


It has a base of 16 and this requires 16 distinct symbols to represent the number.
The base 16 suggests choices of 16 single character digits or symbols.
The first 10 digits are digits of decimal system (0 to 9) and the remaining 6 digits
are denoted by (A to F) where A = 10, B = 11, C = 12, D = 13, E = 14 and F = 15.
Since numbers (0 to 9) and alphabets (A to F) are used to represent the digits in
hexadecimal number system, it is also called the Alphanumeric Number System.
The weight assigned to bits in this system is power of 16.

164

163

162

161

160

16-1

16-2

16-3

16-4

Page 18

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Conversion and Problems:


Conversion between Decimal and Binary
Converting a number from binary to decimal is quite easy. All that is required is to find the
decimal value of each binary digit position containing a 1 and add them up.
For example: convert 101102 to decimal.
10110
\ \ \___________1 x 21 =

\ \____________1 x 22 =

\_______________1 x 24 = 16
22
Another example: convert 110112 to decimal
11011
\ \ \ \_________1 x 20 =

\ \ \__________1 x 21 =

\ \_____________1 x 23 =

\______________1 x 24 =

16
27

The method for converting a decimal number to binary is one that can be used to convert from
decimal to any number base. It involves using successive division by the radix until the dividend
reaches 0. At each division, the remainder provides a digit of the converted number, starting with
the least significant digit.
An example of the process: convert 3710 to binary
37 / 2 = 18

remainder 1

(least significant digit)

Page 19

GE6151 / Computer Programming


18 / 2 = 9

remainder 0

9/2=4

remainder 1

4/2=2

remainder 0

2/2=1

remainder 0

1/2=0

remainder 1

BE(CSE) I SEM / I YEAR

(most significant digit)

The resulting binary number is: 100101


Another example: convert 9310 to binary
93 / 2 = 46

remainder 1

(least significant digit)

46 / 2 = 23

remainder 0

23 / 2 = 11

remainder 1

11 / 2 = 5

remainder 1

5/2=2

remainder 1

2/2=1

remainder 0

1/2=0

remainder 1 (most significant digit)

The resulting binary number is: 1011101

Convert the binary number 10110101 to a hexadecimal number


Divide into groups for 4 digits

1011 0101

Convert each group to hex digit

B
B516

Another example: Convert the binary number 0110101110001100 to hexadecimal

Page 20

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Divide into groups of 4 digits

0110 1011 1000 1100

Convert each group to hex digit

B
8
C
6B8C16

To convert a hexadecimal number to a binary number, convert each hexadecimal digit into a
group of 4 binary digits.
Example: Convert the hex number 374F into binary
3
Convert the hex digits to binary

0011 0111 0100 1111


00110111010011112

Hexadecimal-to-decimal conversion
One way to find the decimal equivalent of a hexadecimal number is to first convert the
hexadecimal number to binary and then convert from binary to decimal.
Convert the hexadecimal number 1C to decimal:
1C
0001 1100 = 24+ 2 + 2 = 16 +8+4 = 28
Decimal-to-hexadecimal conversion

Repeated division of a decimal number by 16 will produce the equivalent hexadecimal


number, formed by the remainders of the divisions.
The first remainder produced is the least significant digit (LSD).Each successive division
by 16 yields a remainder that becomes a digit in the equivalent hexadecimal number.
When a quotient has a fractional part, the fractional part is multiplied by the divisor to get
the remainder.
Convert the decimal number 650 to hexadecimal by repeated division by 16
650 /16 = 40.625 0.625 x 16 = 10 = A (LSD)
40 /16 = 2.5 0.5 x 16 = 8 = 8
2/16 = 0.125 0.125 x 16 = 2 = 2 (MSD)
The hexadecimal number is 28A
Octal-to-decimal conversion
Since the octal number system has a base of eight, each successive digit position is an increasing
power of eight, beginning in the right-most column with 8. The evaluation of an octal number in

Page 21

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

terms of its decimal equivalent is accomplished by multiplying each digit by its weight and
summing the products.
Lets convert octal number 2374 in decimal number.
Weight
8 8 81 80
Octal number 2 37 4
2374 = (2 x 8) + (3 x 8) + (7 x 81) + (4 x 8) =1276
Decimal-to-octal conversion
A method of converting a decimal number to an octal number is the repeated division-by-8
method, which is similar to the method used in the conversion of decimal numbers to binary or to
hexadecimal. Lets convert the decimal number 359 to octal. Each successive division by 8
yields a remainder that becomes a digit in the equivalent octal number. The first remainder
generated is the least significant digit (LSD).
359/8 = 44.875 0.875 x 8 = 7 (LSD)
44 /8 = 5.5 0.5 x 8 = 4
5/8 = 0.625 0.625 x 8 = 5 (MSD)
The number is 547.
Octal-to-binary conversion
Because each octal digit can be represented by a 3-bit binary number, it is very easy to convert
from octal to binary.
Octal/Binary Conversion
Octal Digit 0 1
2
3
4
5
Binary 000 001
010
011
100
101
Lets convert the octal numbers 25 and 140.
Octal Digit 2
5
1
4
0
Binary
010
101
001
100
000

6
110

7
111

Binary-to-octal conversion
Conversion of a binary number to an octal number is the reverse of the octal-to-binary
conversion.
Lets convert the following binary numbers to octal:
110 101
101 111 001
6
5
= 65
5
7
1
= 571

Page 22

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Need For logical analysis and thinking


Understand the problem
Read the problem statement
Question users
Inputs required
Outputs required
Special formulas
Talk to users
Plan the logic
Visual Design Tools Input
record chart Printer
spacing chart
Hierarchy chart
Flowchart
Verbal Design Tools
Narrative Description
Pseudo code
Code the program
Select an appropriate programming language
Convert flowchart and/or Pseudo code instructions into programming languagestatements
Page 23

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Test the program


Syntax errors
Runtime errors
Logic errors
Test Data Set
Implement the program
Buy hardware
Publish software
Train users
Implementation Styles
Crash
Pilot
Phased
Dual
Maintain the program
Maintenance programmers
Legacy systems
Up to 85% of IT department budget

Algorithm
Definition:
An algorithm is a finite sequence of step by step, well defined, unambiguous instructions
for solving a particular problem.
Algorithm is an English-like representation of the logic which is used to solve the
problem.
Qualities of good algorithm
The following are the primary factors that judge the quality of the algorithm
Time The good algorithm takes less amount of time for producing the desired result.
Memory The good algorithm takes less amount of memory space to execute.
Accuracy The good algorithm has more accuracy than other.
Example: Algorithm to find the greatest among three numbers
Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B. If A is greater Perform step 4 else perform step 5
Page 24

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Step 4: Compare A and C. If A is greater, output A is greatest else output C is greatest


Step 5: Compare B and C. If B is greater, output B is greatest else output C is greatest
Step 6: Stop
1. Write an algorithm to convert the temperature in centigrade to the temperature in
Fahrenheit.
Step 1: Start
Step 2: Read the numeric value of C.
Step 3: Calculate F using Formula F= (9/5)*c+32.
Step 4: Write numeric value of F.
Step 5: Stop
2. Write an algorithm to checking whether a number is even or odd.
1. Read the given number, say x.
2. Divide x by 2.
3. If the remainder is 1, then print x is odd
4. Otherwise print x is even.
5. Stop.

3. Write an algorithm to find the area of circle.


1. Read the value of radius.
2. Calculate area using formula area=3.14*radius*radius.
3. Write the value of radius.
4. Stop.

Pseudo Code:
The pseudo code is one of another program logic planner tool, used for explaining
algorithm.
The pseudo code is just the algorithm written by using programming language syntaxes.
Preparing a pseudo code:
Pseudo code is written using structured English.
In a pseudo code, some terms are commonly used to represent the various actions. For
example, for inputting data the terms may be (INPUT,GET, READ), for outputting data (
OUTPUT, PRINT, DISPLAY), for calculations ( COMPUTE, CALCULATE), for
incrementing ( INCREMENT),
Page 25

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

In addition to words like ADD, SUBTRACT, INITIALIZE used for addition, subtraction,
and initialization, respectively.
It use some terms for conditional statements like IF, ELSE, ENDIF and looping
statements like WHILE, DO WHILE etc.
Example: pseudo code for greatest of three numbers
READ a,b,c
IF (a>b) and (a>c) THEN
WRITE a is big
ELSE IF (B>C) THEN
WRITE b is big
ELSE
WRITE c is big
END IF
Example: find sum of first 100 integers
INITIALIZE SUM to zero
INITIALIZE I to zero
DO WHILE (I <100)
INCREMENT I
ADD I to SUM and store in SUM
END DO WHILE
PRINT SUM
STOP

Flow Chart:
A flowchart is diagrammatic representation of the logic for solving a task.
The purpose of drawing a flowchart is to make the logic of the program clearer in a visual
form.
Since flowchart is a diagrammatic representation, it forms a common medium of
communication.
Flow chart symbols:
Basic symbols:

Page 26

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

It is represented by an oval shape. Every process starts and ends at Some points, so every
flowchart need one start and one end symbol. These blocks should contain simple labels
to indicate the process

It is represented by a parallelogram in a flowchart. It is used to represent the


Inputs given by the user to the process and the output given by the process to the
user. This block should be labeled with a brief description of the input or output.

It is represented by a rectangle. It represents actions, logics and calculations taking place


in a process. The process block represents some operation carried out on an element of
data.

It is represented by a rhombus or a diamond shape in a flowchart. It represents condition


or the decision making step in the flowchart. The result of the decision is a Boolean
value, which is either true or false.

Page 27

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Connector:

It is represented by a circle in a flowchart.It represents the continuation of the flow of


steps when a flowchart continues to the next page.

Arrow: It represents the direction of a flowchart.

Page 28

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Control structure in flow chart:


Sequence structure instructions are executed in linear order.

Selection(branch) Structure it asks a true/ false question and then selects the next
instructions Based on the answer

Page 29

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Loop (Iterative)structure It repeats the execution of a block of instructions until the


condition satisfies

ADVANTAGES OF USING FLOWCHARTS


The benefits of flowcharts are as follows:
1. Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.
2. Effective analysis: With the help of flowchart, problem can be analyzed in more effective way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with
the help of flowchart. It helps the programmer to put efforts more efficiently on that part.
LIMITATIONS OF USING FLOWCHARTS
1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.

Page 30

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes


a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.
GUIDELINES FOR DRAWING A FLOWCHART
a. In drawing a proper flowchart, all necessary requirements should be listed out in logical order.
b. The flowchart should be clear, neat and easy to follow. There should not be any room for
ambiguity in understanding the flowchart.
c. The usual direction of the flow of a procedure or system is from left to right or top to bottom.
d. Only one flow line should come out from a process symbol.

e. Only one flow line should enter a decision symbol, but two or three flow lines, one for each
possible answer, should leave the decision symbol.

f. Only one flow line is used in conjunction with terminal symbol.


g. Write within standard symbols briefly. As necessary, you can use the annotation symbol to
describe data or computational steps more clearly.

h. If the flowchart becomes complex, it is better to use connector symbols to reduce the number
of flow lines. Avoid the intersection of flow lines if you want to make it more effective and
better way of communication.
i. Ensure that the flowchart has a logical start and finish.
j. It is useful to test the validity of the flowchart by passing through it with a simple test data.

Page 31

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

UNIT II
C PROGRAMMING BASICS
Problem formulation - Problem Solving - Introduction to ' C' programming -fundamentals structure of a 'C' program - compilation and linking processes - Constants, Variables - Data
Types - Expressions using operators in 'C' - Managing Input and Output operations - Decision
Making and Branching - Looping statements - solving simple scientific and statistical problems.

Problem formulation
Before attempting to solve a problem, we need to first formulate or define the problem. It is
important to precisely define the problem we intend to solve.
What makes a good problem definition?
It is precise.
It states the objectives (what is required):
the inputs and their characteristics, including initial conditions
the outputs and their desired characteristics, including goal conditions
the relationships between the inputs and the desired outputs

Problem Solving
Problem Solving is the sequential process of analyzing information related to a given situation
and generating appropriate response options.
There are 6 steps that you should follow in order to solve a problem:
1. Understand the Problem
2. Formulate a Model
3. Develop an Algorithm
4. Write the Program
5. Test the Program
6. Evaluate the Solution
STEP 1: Understand the Problem:
The first step to solving any problem is to make sure that we understand the problem that we are
trying to solve. we need to know:

What input data/information is available ?


What does it represent ?
Page 32

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

What format is it in ?
Is anything missing ?
What output information am I trying to produce ?
What do I want the result to look like text, a picture, a graph ?
What am I going to have to compute ?

STEP 2: Formulate a Model:


Now we need to understand the processing part of the problem. Many problems break down into
smaller problems that require some kind of simple mathematical computations in order to
process the data.
STEP 3: Develop an Algorithm:
An algorithm is a precise sequence of instructions for solving a problem.
To develop an algorithm, we need to represent the instructions in some way that is
understandable to a person who is trying to figure out the steps involved. Two commonly used
representations for an algorithm is by using (1) pseudo code, or (2) flow charts.
STEP 4: Write the Program:
Transform the algorithm from step 3 into a set of instructions that can be understood by the
computer. Writing a program is often called "writing code" or implementing an algorithm. So
the code (or source code) is actually the program itself.
STEP 5: Test the Program:
Once we have a program written that compiles, we need to make sure that it solves the problem
that it was intended to solve and that the solutions are correct.
Running a program is the process of telling the computer to evaluate the compiled instructions.
STEP 6: Evaluate the Solution:
Once the program produces a result that seems correct, we need to re-consider the original
problem and make sure that the answer is formatted into a proper solution to the problem.

Introduction to ' C' programming

C is a programming language developed at AT& Ts Bell Laboratories of USA in 1972.


It was designed and written by Dennis Ritchie.
C language features were derived from earlier language called B (Basic Combined
Programming Language BCPL)
C seems so popular is because it is reliable, simple and easy to use.
Page 33

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

A Simple Program
The following program is written in the C programming language.
#include<stdio.h>
main()
{
printf("Programmingin C is easy.\n");
}

Fundamentals
(a) Each instruction in a C program is written as a separate statement. Therefore a complete C
program would comprise of a series of statements.
(b) The statements in a program must appear in the same order in which we wish them to be
executed; unless of course the logic of the problem demands a deliberate jump or transfer of
control to a statement, which is out of sequence.
(c) Blank spaces may be inserted between two words to improve the readability of the statement.
However, no blank spaces are allowed within a variable, constant or keyword.
(d)All statements are entered in small case letters.
(e) C has no specific rules for the position at which a statement is to be written. Thats why it is
often called a free-form language.
(f) Every C statement must end with a ;. Thus ; acts as a statement terminator.
Example:
main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n=3;
r = 8.5 ;
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}

Page 34

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

main( ) is a collective name given to a set of statements. This name has to be main( ), it cannot
be anything else. All statements that belong to main( ) are enclosed within a pair of braces { } as
shown below.
main( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}
main( ) is a function. Every function has a pair of parentheses ( ) associated with it.
Any variable used in the program must be declared before using it. For example,
int p, n ;
float r, si ;
Any C statement always ends with a ;For example,
float r, si ;
r = 8.5 ;
In the statement,
si = p * n * r / 100 ;
* and/ are the arithmetic operators. The arithmetic operators available in C are +, -, * and /. C is
very rich in operators. There are about 45 operators available in C.
- The general form of printf( ) function is,
printf ( "<format string>", <list of variables> ) ;
<format string> can contain,
%f for printing real values
%d for printing integer values
%c for printing character values
In addition to format specifiers like %f, %d and %c the format string may also contain any
other characters. These characters are printed as they are when the printf( ) is executed.
Following are some examples of usage of printf( ) function:
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Rs. %f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
The output of the last statement would look like this...
Page 35

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Prin = 1000
Rate = 8.5
-\n is called newline and it takes the cursor to the next line.
printf( )outputs the values to the screen whereas scanf( ) receives them from the keyboard.
ampersand (&) before the variables in the scanf( )function is a must. &is an Address of
operator. It gives the location number used by the variable in memory.

Structure of C Program
A C program may contain one or more sections given below.

Documentation section
Preprocessor section
Definition section

Global declaration section


main()
{
Declaration part;
Executable part;
}

Sub program section


{
Body of subprogram;
}

i)

Documentation section: It consists 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 lines begins with /* and ending with /* are
Page 36

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

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.

ii)

Ex: # include <stdio.h>,

# define A 10 etc.

iii)

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().

iv)

Every C program must have one main() function, which specify the starting of C
program.
void main()
{
}

Functions must return a value and the term void is used to denote that the main
program does not return a value.
Main contains the following two parts.
v)

Declaration Part : This part is used to declare all the variables that are used in the
executable part of the program and these are called local variables.

vi)

Executable Part : It contains at least one valid C statement. The execution of a


program begins with opening brace { and ends with closing brace }. The closing
brace of the main function is the logical end of the program.

Compilation and linking processes:


To execute a C program, we need to follow the steps:
i)
ii)
iii)
iv)

Creating the Program


Compiling the Program
Linking the Program with System Library
Executing the Program

Page 37

GE6151 / Computer Programming


i)

BE(CSE) I SEM / I YEAR

Creating the Program


Creating the program means entering and editing the program in standard C editor
and save the program with .C as an extension.

ii)

Compiling the Program


This is the process of converting the high level language program into
machine understandable form (Machine language) which is called as
compilation.
We can compile the program by selecting compile from compile menu or
press Alt+f9. After compiling a file with the same name as source code file
but with extension .obj is created.
Here there is a possibility to show errors i.e. Syntax errors, means the
statements written in program are not in proper syntax.

iii)

Linking the program with system library


C Language program is the collection of predefined functions.
These functions are already written in some standard C header files.
Therefore before executing a C program, we need to link with system
library.
Linking the program which creates an executable file .exe (filename same as
source code). This can be done automatically at the time of execution.

iv)

Executing the program


This is the process of running and testing the program with sample data. When you
execute the program, the compiler displays the output of the program and comes back
to the program editor. At this time there is a possibility to show two types of errors
given below.
a) Logical Errors: These are the errors, in which the conditional and control
statements cannot end their match after some sequential execution.
b) Data Errors: These are the errors, in which the input data given, is not in a proper
syntax as specified in input statements.

Constants, Variables:
The alphabets, numbers and special symbols when properly combined form constants,
variables and keywords.
Page 38

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

A constant is an entity that doesnt change whereas a variable is an entity that may
change.
In any program we typically do lots of calculations. The results of these calculations are
stored in computers memory, the value stored in each location may change the names
given to these locations are called variable names.
Consider the following example.
Here 3 is stored in a memory location and a name x is given to it. Then we are assigning
a new value 5 to the same memory location x. This would overwrite the earlier value 3,
since a memory location can hold only one value at a time.
Since the location whose name is x can hold different values at different times x is known
as a variable. As against this, 3 or 5 do not change, hence are known as constants

Types of C Constants
C constants can be divided into two major categories:
(a)Primary Constants
(b) Secondary Constants

Page 39

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Rules for Constructing Integer Constants


(a) An integer constant must have at least one digit.
(b)It must not have a decimal point.
(c)It can be either positive or negative.
(d)If no sign precedes an integer constant it is assumed to be positive.
(e)No commas or blanks are allowed within an integer constant.
(f)The allowable range for integer constants is -32768 to 32767.
Ex.: 426
+782
-8000
-7605
Rules for Constructing Real Constants
Real constants are often called Floating Point constants. The real constants could be
written in two formsFractional form and Exponential form.
Following rules must be observed while constructing real constants expressed in
fractional form:
(a)A real constant must have at least one digit.
(b)It must have a decimal point.
Page 40

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

(c)It could be either positive or negative.


(d)Default sign is positive.
(e)No commas or blanks are allowed within a real constant.
Ex.:

+325.34
426.0
-32.76
-48.5792
The exponential form of representation of real constants is usually used if the value of the
constant is either too small or too large.
In exponential form of representation, the real constant is represented in two parts. The
part appearing before e is called mantissa, whereas the part following e is called
exponent.
Following rules must be observed while constructing real constants expressed in exponential
form:
(a)The mantissa part and the exponential part should be separated by a letter e.
(b)The mantissa part may have a positive or negative sign.
(c)Default sign of mantissa part is positive.
(d)The exponent must have at least one digit, which must be apositive or negative
Integer. Default sign is positive.
(e)Range of real constants expressed in exponential form is-3.4e38 to 3.4e38.
Ex.: +3.2e-5
4.1e8
-0.2e+3
-3.2e-5
Rules for Constructing Character Constants
(a) A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas. Both the inverted commas should point to the
left.
For example, A is a valid character constant whereas A is not.
(b) The maximum length of a character constant can be 1character.
Ex.: 'A'
'I'
'5'
'='

Page 41

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Types of C Variables:
An entity that may vary during program execution is called a variable. Variable names
are names given to locations in memory.
These locations can contain integer, real or character constants. In any language, the
types of variables that it can support depend on the types of constants that it can handle.
This is because a particular type of variable can hold only the same type of constant.
For example, an integer variable can hold only an integer constant, a real variable can
hold only a real constant and a character variable can hold only a character constant.
Rules for Constructing Variable Names:
(a)A variable name is any combination of 1 to 26 alphabets, digits or underscores. Some
compilers allow variable names whose length could be up to 247 characters. Still, it
would be safer to stick to the rule of 31 characters.
(b)The first character in the variable name must be an alphabet or underscore.
(c)No commas or blanks are allowed within a variable name.
(d)No special symbol other than an underscore (as in gross_sal)can be used in a variable
name.
Ex.: si_int
m_hra
pop_e_89
The Programming language C has two main variable types

Local Variables
Global Variables

Local Variables

Local variables scope is confined within the block or function where it is defined. Local
variables must always be defined at the top of a block.
When a local variable is defined - it is not initalised by the system, you must initalise it
yourself.
When execution of the block starts the variable is available, and when the block ends the
variable 'dies'.

Check following example's output


main()
{
int i=4;
Page 42

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

int j=10;
i++;
if (j > 0)
{
/* i defined in 'main' can be seen */
printf("i is %d\n",i);
}
if (j > 0)
{
/* 'i' is defined and so local to this block */
int i=100;
printf("i is %d\n",i);
}/* 'i' (value 100) dies here */
printf("i is %d\n",i); /* 'i' (value 5) is now visible.*/
}
This will generate following output
i is 5
i is 100
i is 5
Here ++ is called incremental operator and it increase the value of any integer variable by 1.
Thus i++ is equivalent to i = i + 1;
-- operator also which is called decremental operator and it decrease the value of any integer
variable by 1. Thus i-- is equivalent to i = i - 1;
Global Variables
Global variable is defined at the top of the program file and it can be visible and modified by any
function that may reference it.
Global variables are initalised automatically by the system when you define them.
Data Type

Initializer

int

char

'\0'

float

pointer

NULL
Page 43

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

If same variable name is being used for global and local variable then local variable takes
preference in its scope. But it is not a good practice to use global variables and local variables
with the same name.
int i=4;
/* Global definition */
main()
{
i++;
/* Global variable */
func();
printf( "Value of i = %d -- main function\n", i );
}
func()
{
int i=10; /* Local definition */
i++;
/* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}
This will produce following result
Value of i = 11 -- func() function
Value of i = 5 -- main function
i in main function is global and will be incremented to 5. i in func is internal and will be
incremented to 11. When control returns to main the internal variable will die and and any
reference to i will be to the global.

Data Types:

Data type is the type of the data that are going to process within the program.

C supports different data types; each data type may have predefined memory
requirement and storage representation.
C Data types: There are four data types in C language. They are,
S.no Types

Data Types

Basic data types

int, char, float, double

User defined data type typedef, enum

Derived data type

pointer, array, structure, union

Page 44

GE6151 / Computer Programming


4

Void data type

BE(CSE) I SEM / I YEAR


void

INTEGER
These are whole numbers, both positive and negative. Unsigned integers (positive values
only)are supported. In addition, there are short and long integers.
The keyword used to define integers is,
int
An example of an integer value is 32. An example of declaring an integer variable called
sum is,
int sum;
sum = 20;

C offers a variation of the integer data type called short and long integer values. The
intention of providing these variations is to provide integers with different ranges
wherever possible. Short and long integers would usually occupy two and four bytes
respectively.
long variables which hold long integers are declared using the keyword long, as in,
longint i ;
longint abc ;

long integers cause the program to run a bit slower, but the range of values that we can
use is expanded tremendously. The value of a long integer typically can vary from 2147483648 to+2147483647.
short integer variables are declared as,
shortint j ;
shortint height ;
C allows the abbreviation of short int to short and of long int to long. So the
declarations made above can be written as,
long i ;
long abc ;
short j ;
short height ;

Page 45

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

CHARACTER
These are single characters. The keyword used to define character variables is,
char

An example of a character value is the letter A. An example of declaring a character


variable called letter,
Char letter;
letter= 'A';

Note the assignment of the character A to the variable letter is done by enclosing the
value in single quotes.

Signed and Unsigned chars, both occupying one byte each, but having different ranges.
A signed char is same as an ordinary char and has a range from-128 to +127; whereas,
an unsigned char has a range from 0 to255.

FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The
keyword used to define float variables is,
float

An example of a float value is 34.12. An example of declaring a float variable called


money is,
Float money;
money =0.12;

A float occupies four bytes in memory and can range from -3.4e38to +3.4e38.
If this is insufficient then C offers a double data type that occupies 8 bytes in memory
and has a range from -1.7e308 to+1.7e308.
A variable of type double can be declared as,
double a, population ;

Page 46

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

If the situation demands usage of real numbers that lie even beyond the range offered by
double data type, then there exists along double that can range from -1.7e4932 to
+1.7e4932.
A long double occupies 10 bytes in memory.

User defined data type


Typedef
Typedef is a keyword used in C language to assign alternative names to existing types.
Its mostly used with user defined data types, when names of data types get slightly
complicated.
Syntax:
Typedef existing_name alias_name
Example:
Typedef int marks;
Marks m1,m2,m3;
Enumeration data type:
Enumeration data type consists of named integer constants as a list.
It start with 0(zero) by default and value is incremented by 1 for the sequential identifiers
in the list.
Page 47

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

It is the way of attaching a number with a variable name.


Enum syntax in C:
enum identifier [value1, value2,.valuen];
Enumexample :
enum month { Jan, Feb, Mar };
/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
enum month { Jan = 20, Feb, Mar };
/* Jan, Feb and Mar variables will be assigned to 20, 21 and 22 respectively by default */
C enum example program:
#include <stdio.h>
int main()
{
enum MONTH { Jan = 0, Feb, Mar };
enum MONTH month = Mar;
if(month == 0)
printf("Value of Jan");
else if(month == 1)
printf("Month is Feb");
if(month == 2)
printf("Month is Mar");
}
Output:
Month is March
Derived data type:
Array, pointer, structure and union are called derived data type.
Void data type:
Void is an empty data type that has no value. This can be used in functions and pointers.

Page 48

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Expressions using operators in 'C':

An operator is a symbol that specified an operation to be performed on the operands.

Some operators require two operands called binary operators, while other acts upon only
one operand called unary operator.
Operators, functions, constants and variables are combined together to form expressions.
Example: A + B * 5
where,
+, * - operators
A, B - variables
5 constant
A + B * 5 - expression

Types of C operators:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
1. Arithmetic operators:
These operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.
S.no Operator Operation
1 +
Addition
2 Subtraction
3 *
multiplication
4 /
Division
5 %
Modulus
Example program for C arithmetic operators:

# include <stdio.h>
Page 49

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

1 void main()
2 {
int a=40,b=20,add,sub,mul,div,mod;
3
add=a+b;
4
sub=a-b;
5
mul=a*b;
6
div=a/b;
7
mod=a%b;
8
printf("Addition of a, b is : %d\n",add);
9
printf("Subtraction of a, b is : %d\n",sub);
10
printf("Multiplication of a, b is : %d\n",mul);
11
printf("Division of a, b is : %d\n",div);
12
printf("Modulus of a, b is : %d\n",mod);
13 }

2. Assignment operators and short hand assignment operators:


The values for the variables are assigned using assignment operators. For example, if the
value 10 is to be assigned for the variable sum, it can be done like below
Sum=10
Below are some of other assignment operators:
Operator
Simple operator

Example
= sum = 10

+= sum+=10
-= sum = 10
*= sum*=10
Compound assignment operator /+ sum/=10
%= sum%=10
&= sum&=10
^= sum^=10

Explanation
Value 10 is assigned to variable
sum
This is same as sum = sum+10
This is same as sum = sum 10
This is same as sum = sum*10
This is same as sum = sum/10
This is same as sum = sum%10
This is same as sum = sum&10
This is same as sum = sum^10

Example program for assignment operators:


# include <stdio.h>
int main()
{
Page 50

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i;
/*This is same as Total = Toatal+i*/
}
printf("Total = %d",Total);
}
Output: Total = 45

3. Relational operators:
These operators are used to find the relation between two variables. That is used to
compare the value of two variables.
Operator Example
>

x>y

<

x<y

>=

x >= y

<=

x <= y

==

x == y

!=

x != y

Example program for relational operators:


#include <stdio.h>
int main()
{
int m=40,n=20;
if(m==n){
printf("m and n are equal");
}
else{
printf("m and n are not equal");
}
}
Page 51

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Output:
m and n are not equal
4. Logical operators:
These operators are used to perform logical operations on the given two variables
Operator Example
&&
x && y
||
x || y
!
x != y)
Example program for logical operators:
1
2
3
4
5
6
7
8

#include <stdio.h>
int main()
{
int m=40,n=20;
if(m>n&&m!=0){
printf("m is greater than n and not equal to 0");
}
}

Output:m is greater than n and not equal to 0


5. Bitwise operators:
These operators are used to perform bit operations on given two variables
Truth table for bitwise operation
Bitwise operators
X
0
0
1
1

y
0
1
0
1

x/y
0
1
1
1

x&y
0
0
0
1

x^y
0
1
1
0

Operator Explanation
&
Bitwise AND
|
Bitwise OR
~
Bitwise NOT
^
XOR
<<
Left Shift
>>
Right Shift

Example program for bitwise operators:


1
2
3

#include <stdio.h>
int main()
{
Page 52

GE6151 / Computer Programming


4
5
6
7
8
9
10
11
12 }

BE(CSE) I SEM / I YEAR

int m=40,n=20,AND_opr,OR_opr,XOR_opr;
AND_opr=(m&n);
OR_opr=(m|n);
XOR_opr=(m^n);
printf("AND_opr value = %d\n",AND_opr);
printf("XOR_opr value = %d\n",XOR_opr);
printf("OR_opr value = %d\n",OR_opr);

Output:
AND_opr value = 0
XOR_opr value = 60
OR_opr value = 60
6. Conditional operators:
Conditional operators return one value if condition is true and returns other value when
the condition is false.
This operator is also called as ternary operator
Syntax
: (Condition ? true value : false value);
Example
: (A>100 ? 0 : 1);
Here, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
Example program for conditional / ternary operators:
#include <stdio.h>
int main()
{
int x=1,y;
y=(x==1?2:0);
printf("x value is %d\n",x);
printf("y value is %d",y);
}
Output:x value is 1
y value is 2

Page 53

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

7. Increment and decrement operators:


These operators are used to either increase or decrease the value of the variable by one.
Syntax:
++varname; (or)
varname--; (or)
--varname; (or)
varname--;
Example: ++i, i++, --i, i
//Example for increment operators
#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d\n",i);
i++;
}
}
//Example for decrement operators
#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d\n",i);
i--;
}
}
8. Special operators:
Below are some of special operators that the C language offers.
S.no

Operators

&

Description
This is used to get the address of the variable.
Example:
&a will give address of a.
This is used as pointer to a variable.
Example: * a where, * is pointer to the variable a.
Page 54

GE6151 / Computer Programming

Size of ()

BE(CSE) I SEM / I YEAR

This gives the size of the variable.


Example: size of (char) will give us 1.

Managing Input and Output operations:


Printf ():
printf() is actually a function (procedure) in C that is used for printing variables and text, where
text appears in double quotes "", it is printed without modification. There are some exceptions
however. This has to do with the \ and % characters. These characters are modifier's, and for the
present the \ followed by the n character represents a newline character.
Example:
#include <stdio.h>
main()
{
printf("Programming in C is easy.\n");
printf("And so is Pascal.\n");
}
@ Programming in C is easy.
And so is Pascal.
FORMATTERS for printf are,
Cursor Control Formatters
\n
newline
\t
tab
\r
carriage return
\f
form feed
\v
vertical tab
Scanf ():
Scanf () is a function in C which allows the programmer to accept input from a keyboard.
Example:
#include <stdio.h>
main() /* program which introduces keyboard input */
{
int number;
printf("Type in a number \n");
scanf("%d", &number);
printf("The number you typed was %d\n", number);
Page 55

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

}
FORMATTERS FOR scanf()
The following characters, after the % character, in a scanf argument, have the following effect.
d
read a decimal integer
o
read an octal value
x
read a hexadecimal value
h
read a short integer
l
read a long integer
f
read a float value
e
read a double value
c
read a single character
s
read a sequence of characters
[...]
read a character string. The characters inside the brackets.
ACCEPTING SINGLE CHARACTERS FROM THE KEYBOARD
Getchar, Putchar
getchar() gets a single character from the keyboard, and putchar() writes a single character from
the keyboard.
Example:
The following program illustrates this,
#include <stdio.h>
main()
{
int i; int ch;
for( i = 1; i<= 5; ++i ) {
ch = getchar();
putchar(ch);
}
}
The program reads five characters (one for each iteration of the for loop) from the keyboard.
Note that getchar() gets a single character from the keyboard, and putchar() writes a single
character (in this case, ch) to the console screen.

Decision Making and Branching:

In decision control statements ( if else and nested if ), group of statements are executed
when condition is true. If condition is false, then else part statements are executed.
There are 4 types of decision making control statements in C language. They are,

Page 56

GE6151 / Computer Programming


1.
2.
3.
4.

BE(CSE) I SEM / I YEAR

if statements
if else statements
nested if statements
If ..else..if ladder

Statement
if
statement

Syntax.
if(condition)
{
Statements;
}

Description
In these type of
statements, if condition
is true, then respective
block of code is
executed.

ifelse
statement

if(condition)
{
Statement1;
Statement2;
}
else
{
Statement3;
Statement4;
}
if(condition1)
{
if (condition2)
{
Statement 2;
}
else
{ statement 3;
}
else
{
if(condition3)
{
Statement 4;
}
else

In these type of
statements, group of
statements are executed
when condition is true.
If condition is false,
then
else
part
statements
are
executed.

nested if

If condition 1 is true
then condition 2 is
checked and statements
are executed.
If
condition1
is false
then else part is
executed.

Page 57

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

{ statement5;
}
}
If ..else..if if(condition1)
{
ladder
Statement1;
}
else
if(condition2)
{
Statement2;
}
else
if(condition3)
{Statement 3;}
else
Statement4;

The
conditional
expressions
are
evaluated from the top
downward. As soon as
a true condition is
found, the statement
associated with it is
executed, and the rest
of the ladder is
bypassed. If none of the
conditions is true, then
the final else statement
will be executed.

Example program for if:


In if control statement, respective block of code is executed when condition is true.
void main()
{
int m=40,n=40;
if(m==n)
{
printf("m and n are equal");
}
}
Output: m and n are equal
Example program for C if else:
In C if else control statement, group of statements are executed when condition is true. If
condition is false, then else part statements are executed.
#include <stdio.h>
int main()
{
int m=40,n=20;
if(m==n)
Page 58

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Output: m and n are not equal
Example program for C nested if:
In nested if control statement, if condition 1 is true, then condition 2 is checked and
statements are executed if it is true. If condition 2 also gets failure, then else part is executed.
#include <stdio.h>
int main()
{
int m=40,n=20;
if(m!=n)
{
If(m>n)
{
printf("m is greater than n");
}
else
{
printf("m is less than n");
}
else
{
printf("m is equal to n");
}
}
}
Output: m is greater than n
Example program for C if else if ladder:
In this control statement, if condition 1 is false, then condition 2 is checked and statements
are executed if it is true. If condition 2 also gets failure, then else part is executed.
Page 59

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

#include <stdio.h>
int main()
{
int m=40,n=20;
if(m>n)
{
printf("m is greater than n");
}
elseif(m<n){
printf("m is less than n");
}
else
{
printf("m is equal to n");
}
}
Output:
m is greater than n
Switch case statement
Switch statement is used to execute a block of statements depending on the value of a
variable or an expression.
If the switch value matches with any case value the corresponding case will execute.
If none of the conditions is met then default block will be executed.
Syntax:
switch(expression)
{case constant-expression1 :
statement(s);
break;/* optional */
case constant-expression2 :
statement(s);
break;/* optional */
/* you can have any number of case statements */
default:/* Optional */
statement(s);
}

Page 60

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

/* Example of switch statement */


#include <stdio.h>
void main()
{ char Grade = 'B';
switch( Grade )
{ case 'A' : printf( "Excellent\n" );
break;
case 'B' : printf( "Good\n" );
break;
case 'C' : printf( "Average\n" );
break;
case 'D' : printf( "Better\n" );
break;
default :printf( "No such grade.\n" );
break;
}
}
This will produce following result:

Good

Looping statements

Iteration or looping is a process of repeating the same set of statements again and again
until the specified condition is true.
A loop statement allows to execute a statement or group of statements multiple times.

Page 61

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

while loop
A while loop statement in C programming language repeatedly executes a block of statement as
long as a given condition is true.
Syntax:
while(condition)
{
statement(s);
}

Here, statement(s) may be a single statement or a block of statements.


The condition may be any expression, and true is any nonzero value. The loop iterates
while the condition is true.

When the condition becomes false, program control passes to the line immediately
following the loop.

#include<stdio.h>
void main ()
{int a =10;
while( a <20)
{
printf("value of a: %d\n", a);
a++;
}
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
Page 62

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Do While Loop
The do...while loop in C programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.
Syntax:
do
{
statement(s);
}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s)
in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in
the loop execute again. This process repeats until the given condition becomes false.

/* Example */
#include<stdio.h>
void main ()
{
Page 63

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

int a =10;
do
{printf("value of a: %d\n", a);
a = a +1;
}while( a <20);
}
Result is
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
for( initialization ; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
1. The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after the
for loop.

Page 64

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

3. After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables.
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the for loop terminates.

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
Page 65

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

value of a: 19

UNCONDITIONAL STATEMENTS OR JUMP STATEMENTS


break Statement
In C programming, break is used in terminating the loop immediately after it is encountered. The
break statement is used with conditional if statement.
Syntax of break statement
break;
The break statement can be used in terminating all three loops for, while and do...while loops.

The figure below explains the working of break statement in all three type of loops.

//Example
#include <stdio.h>
main()
{
int i = 1;
while ( i> =10 )
Page 66

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

{
printf("Hello %d\n", i );
i = i +1;
if(i == 6 )
{
break;
}
}
}
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
continue Statement
It is sometimes desirable to skip some statements inside the loop or skip 1 iteration of loop. In
such cases, continue statements are used.
Syntax of continue Statement
continue;
Just like break, continue is also used with conditional if statement.

For better understanding of how continue statements works in C programming. Analyze the
figure below which bypasses some code/s inside loops using continue statement.

Page 67

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

#include
main()
{ int i;
int j = 10;
for(i = 0; i<= j; i ++ )
{
if(i == 5 )
{
continue;
}
printf("Hello %d\n", i );
}

}
goto statement
The goto statement is used to alter the normal sequence of program execution by transferring
control to some other part of the program unconditionally. In its general form, the goto statement
is written as
Syntax:
{
.
go to label;
Page 68

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

.
.
Label:
Statements;
}
where the label is an identifier that is used to label the target statement to which the
control is transferred. Control may be transferred to anywhere within the current function. The
target statement must be labeled, and a colon must follow the label. Thus the target statement
will appear as
Each labeled statement within the function must have a unique label, i.e., no two statement can
have the same label.

Simple scientific and statistical problems


Program for Quadratic equation
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c,d;
float root1,root2;
printf("Enter the values of a,b,c\n");
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
if(d>=0)
Page 69

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

{
root1=(-b+sqrt(d))/(2*a);
root2=(+b+sqrt(d))/(2*a);
printf("The roots of the values are a=%d,b=%d,c=%d,root1=%f,root2=%f\n",a,b,c,root1,root2);
}
else
{
printf("The roots are imaginary");
}
getch();
}
Program for area of triangle
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int s,a,b,c;
float area;
clrscr();
printf("Enter the value for a,b,c\n");
scanf("%d%d%d",&a,&b,&c);
s=(a+b+c)/2;
printf("s=%d\n",s);
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("area of triangle=%f",area);
getch();
}
Scientific problem solving using decision making & looping
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
double a, b, c, d, e, x1, x2;
/* Read input data */
printf("\na = ");
scanf("%lf", &a);
printf("b = ");
Page 70

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

scanf("%lf", &b);
printf("c = ");
scanf("%lf", &c);
/* Test for a = 0. */
if (a == 0.)
{
printf("\nError: a = 0.\n");
exit(1);
}
/* Perform calculation */
e = b * b - 4. * a * c;
if (e > 0.) // Test for real roots
{
/* Case of real roots */
d = sqrt(e);
x1 = (-b + d) / (2. * a);
x2 = (-b - d) / (2. * a);
printf("\nx1 = %12.3e x2 = %12.3e\n", x1, x2);
}
else
{
/* Case of complex roots */
d = sqrt(-e);
x1 = -b / (2. * a);
x2 = d / (2. * a);
printf("\nx1 = (%12.3e, %12.3e) x2 = (%12.3e, %12.3e)\n",
x1, x2, x1, -x2);
}
return 0;
}

UNIT III ARRAYS AND STRINGS


Arrays - Initialization - Declaration - One dimensional and Two dimensional arrays. StringString operations - String Arrays. Simple programs- sorting- searching - matrix operations.
ARRAYS:

Page 71

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

In C programming, one of the frequently arising problem is to handle similar types of data. For
example: If the user want to store marks of 100 students. This can be done by creating 100
variable individually but, this process is rather tedious and impracticable. These type of problem
can be handled in C programming using arrays.
An array is a collection of similar data items that are stored under a common name.
A value in an array is identified by index or subscript enclosed in square brackets with
array name.
An array is used to store large amount of data of similar data types.
Example:
int abc[50];

// It can store 50 integer items under a common name abc.

float xyz[20];// It can store 20 floating point items under a common name xyz.
Arrays can be classified into
1. One-dimensional arrays
2. Two dimensional arrays
3. Multi dimensional arrays
1.One Dimensional array (1D Array)
The collection of data items can be stored under a one variable name using only one
subscript; such a variable is called one dimensional array.
Declaration of one-dimensional array:
data_type array_name[array_size];
For example:

int age[5];

Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array
age. All elements in an array are of the same type (int).
Array elements
Size of array defines the number of elements in an array.
Elements in the age array storage location are shown in figure.

Page 72

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Note that, the first element is numbered 0, second element is numbered 1 and so on.
Initialization of one-dimensional array:
The array can be initialized in the following two ways.
1. At Compile time
2. At run time
1. Initialization during compile time

Syntax:
Example:

data type array name[size]= { List of values};


int age[5]= {2,4,34,3,4};

It is not necessary to define the size of arrays during initialization.


Example: int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number of elements of
an array.

2. Initialization during run time

int a[5];
for (i=0;i<5;i++)
{
printf( enter the values for a[%d],i);
scanf(%d,&a[i]);
}
Example program to find average marks obtained by a class of 30 students in a test.
main( )
{
Page 73

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

int avg, sum = 0 ;


int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i<= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ; /* store data in array */
}
for ( i = 0 ; i<= 29 ; i++ )
sum = sum + marks[i] ; /* read data from an array*/
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
}
2. Two Dimensional array (2D Array):
Two dimensional arrays are used in situation where a table of values or matrix to be
stored in array.
Two pairs of square brackets required for two dimensional arrays.
First subscript refers row size and second subscript refers column size.
Declaration of 2D array:
Syntax:

Datatype arrayname[rowsize][columnsize];

Example:

int A[3][3]; //it creates 3x3 matrix

Figure shows 3X3 matrix:

Initialization of 2D array during Compilation time:


Page 74

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

int A[3][3]={11,12,13,14,15,16,17,18,19}
Element 11 can be referred as A[0][0]
Element 12 can be referred as A[0][1]
Element 13 can be referred as A[0][2]
Element 14 can be referred as A[1][0]
Element 15 can be referred as A[1][1] and so on.
Another way to define 2-D array is:
int A[3][3]={
{11,12,13},
{14,15,16},
{17,18,19}
}
The above mentioned method increases the readability of the matrix.

Initialization of 2D array during run time:


int a[3][3],i,j;
printf("Enter the First matrix");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
Example program for 2 dimensional array:
main( )
{
int stud[4][2] ;
int i, j ;
for ( i = 0 ; i<= 3 ; i++ )
{
printf ( "\n Enter roll no. and marks" ) ;
scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;
}
for ( i = 0 ; i<= 3 ; i++ )
printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;
Page 75

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

}
3. Multi dimensional array (3D Array)
data_type array_name[d1][d2][d3][d4][dn]; //Where dn is the size of last
dimension.
Example:

int table[5][5][20];
float arr[5][6][5][6][5];

Figure show a view of 3D array

3D Array Conceptual View

Example program for 3 dimensional array:


#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k;
int arr[3][3][3]=
{ { {11, 12, 13},{14, 15, 16}, {17, 18, 19} },
{{21, 22, 23},{24, 25, 26}, {27, 28, 29} },
{ {31, 32, 33},{34, 35, 36}, {37, 38, 39} },
};
Page 76

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

printf(":::3D Array Elements:::\n\n");


for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{ for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
} printf("\n");
}
}

String

The way a group of integers can be stored in an integer array, similarly a group of
characters can be stored in a character array. Character arrays are many a time also called
strings.
Character arrays or strings are used by programming languages to manipulate text such as
words and sentences.
A string constant is a one-dimensional array of characters terminated by a null ( \0 ).
For example,
char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;
A string is a array of characters. Any group of characters(except the double quote
sign)defined between double quotation marks is a constant string.
Eg: Man is obviously made to think
/* Program to demonstrate printing of a string */
main( )
{
char name[ ] = "Klinsman" ;
inti = 0 ;
while ( i<= 7 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
And here is the output...
Klinsman

Page 77

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

DECLARING AND INITIALIZING STRING VARIABLES

A string variable is any valid C variable name and is always declared as an array.

The general form of declaration of a string variable is


char string_name[size];

Eg:

char city[10];
char name[30];

When the compiler assigns a character string to a character array, it automatically supplies a null
character (\0) at the end of the string. Therefore, the size should be equal to the maximum
number of characters in the string plus one.

String operations
String.h header file supports all the string functions in C language. All the string functions are
given below.
S.no String functions Description
1

strcat(str1, str2)

Concatenates str2 at the end of str1.

strcpy(str1, str2) Copies str2 into str1

strlen(strl)

Gives the length of str1.

strcmp(str1, str2)

Returns 0 if str1 is same as str2. Returns <0 if strl< str2. Returns >0 if
str1 > str2.

strcmpi(str1,str2)

Same as strcmp() function. But, this function negotiates case. A and


a are treated as same. i indicates ignore case.

strrev()

reverses the given string

strlwr()

converts string to lowercase

strupr()

converts string to uppercase


Page 78

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

strset()

sets all character in a string to given character

10

strchr(str1, char) Returns pointer to first occurrence of char in str1.

11

strrchr()

last occurrence of given character in a string is found

12

strstr(str1, str2)

Returns pointer to first occurrence of str2 in str1.

13

strdup()

duplicates the string

14

strncat()

appends a portion of string to another

15

strncpy()

copies given number of characters of one string to another

16

strtok()

tokenizing given string using delimiter

17

strncmp()

Compares at the most n characters of two strings s1 and s2.

18

strncmpi()

Compares at the most n characters of two strings s1 and s2 without case


sensitivity.

19

strnset()

Sets the first n characters of the string s to the character ch

Strlen() function
The strlen() is used to find the length of a string. The input can be a string literal constant
or a character array holding a string or a character pointer pointing to a string.
Syntax : strlen(string);
Example program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[20] = hello;
printf(length of the string is :%d,strlen(str));
printf(length of the string is :%d,strlen(welcome);
}

Page 79

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Output is
length of the string is: 5
length of the string is:7
strcpy() function
The strcpy() function copies the source string to the destination string.
Syntax : strcpy(deststring, srcstring);
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20] = hello;
char str2[20];
strcpy(str2,str1);
printf(source string is :%s,str1);
printf(destination string is :%s,str2);
}
Output is
source string is: hello
destination string is:hello
strcat() function
The strcat function concatenates one string with another. It appends a source string to the
destination string.
Syntax : strcat(deststring, srcstring);
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20] = hello;
char str2[20] =world
strcat(str1,str2);
Page 80

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

printf(source string is :%s,str1);


printf(destination string is :%s,str2);
}
Output is
source string is: hello
destination string is: helloworld
strcmp() function
The strcmp function compares two strings. It returns 0 if str1 and str2 are equal.
It returns >0 if str1 is greater than str2. It returns <0 is str1 is lesser than str2.
It returns the ASCII difference of the first dissimilar corresponding characters if two
strings are greater or lesser or zero if two strings are equal.
Syntax : strcmp(string1,string2);
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20] = Apple;
char str2[20] =Computer
int res;
res=strcmp(str1,str2)
if(res==0)
puts(strings are equal);
else
puts(strings are not equal);
}
strrev() function
The strrev function reverses all the characters of a string except the terminating null
character.
Syntax : strrev(string);
Example program:
#include<stdio.h>
#include<string.h>
Page 81

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

void main()
{
char str[20] = hello;
printf(reverse string is :%s,strrev(str));
}
Output is
reverse string is : olleh
strlwr() function
The strlwr function converts all the letters in a string to lowercase.
Syntax : strlwr(string);
Example program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[20] = HELLO;
printf(reverse string is :%s,strlwr(str));
}
Output is
Lower case is : hello
strupr() function
The strupr function converts all the letters in a string to uppercase.
Syntax : strupr(string);

Example program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[20] = hello;
printf(reverse string is :%s,strupr(str));
}
Page 82

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Output is
Upper case is : HELLO
strset() function
The strset function sets all characters in a string to a specific character.
Syntax : strset(string, char);
Example program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[20] = hello;
char a=*;
strset(str,a)
puts(str)
}
Output is
*****
strchr() function
The strchr function scans a string in the forward direction for the first occurrence of a
given character. If the character is found, it returns a pointer. If the character is not
found it returns NULL.

Syntax : strchr(string, char);


Example : char str[20]=welcome;
char a=c;
strchr(str,a);
strrchr() function
The strrchr function locates the last occurrence of a character in a given string. If the
character is found, it returns a pointer. If the character is not found it returns NULL.
Syntax : strrchr(string, char);

Page 83

GE6151 / Computer Programming


Example :

BE(CSE) I SEM / I YEAR

char str[20]=welcome;
char a=o;
strrchr(str,a);

strstr() function
The strstr function finds the first occurrence of a string in another string. If the string is
found, it returns a pointer. If the string is not found it returns NULL.
Syntax : strstr(string1,string2);
Example :

char str1[20]=hello world computer;


char str2[20]=world
strstr(str1,str2);

strcmpi(str1,str2)

Same as strcmp() function. But, this str1=apple


function negotiates case. A and a str2=Apple
are treated as same. i indicates ignore O/P : Both Strings are equal.
case.

strncat(str1,str2,n)

appends a portion of string to another

strncpy(str1,str2,n)

copies given number of characters of str2=hello n=3


one string to another
O/P : hel

strncmp(str1,str2,n)

str1=hello, str2=krishna
n=5
O/P : hellokrish

Compares at the most n characters of two str1=Apple


strings s1 and s2.
str2=Apple n=3
O/P : Both Strings are equal.

strncmpi(str1,str2,n) Compares at the most n characters of two str1=apple


strings s1 and s2 without case sensitivity. str2=Apple n=3
O/P : Both Strings are equal.
strnset(str1,char,n)

Sets the first n characters of the strings to str1=apple char =&, n=3
the character
O/P : &&&le

Example program

Page 84

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

#include<stdio.h>
#include<string.h>
int main ()
{
char str1[12]="Hello";
char str2[12]="World";
char str3[12];
intlen;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len=strlen(str1);
printf("strlen(str1) : %d\n",len);
return0;
}

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

String Arrays
Strings are declared in C in similar manner as arrays. Only difference is that, strings are
of char type.
Eg: char s[5];

Page 85

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Strings can also be declared using pointer.


Eg: char *p
Initialization of strings
In C, string can be initialized in different number of ways.
char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};

String can also be initialized using pointers


char *c="abcd";

Sorting:
Sorting is a technique to rearrange the elements of a list in ascending or descending can be done
on names, numbers and records.
Types of Sorting:
Page 86

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Selection sort
Bubble sort
Insertion sort
Merge sort
Quick sort
Shell sort
Radix sort

Selection sort:

In this technique, the first element is selected and compared with all other elements. If
any other element is less than the first element swapping should take place.

By the end of this comparison, the least element most top position in the array. This is
known as pass1.

In pass II, the second element is selected and compared with all other elements.
Swapping takes place if any other element is less than selected element.

This process continuous until array is sorted.

Bubble sort

This technique compares last element with the preceding element. If the last element is
less than that of preceding element swapping takes place.

Then the preceding element is compared with that previous element. This process
continuous until the II and I elements are compared with each other. This is known as
pass 1.

Insertion sort

In this method, sorting is done by inserting elements into an existing sorted list.

Initially, the sorted list has only one element. Other elements are gradually added into the
list in the proper position.

Merge sort

In this method, the elements are divided into partitions until each partition has sorted
elements.

Then, these partitions are merged and the elements are properly positioned to get a fully
sorted list.

Quick sort

Page 87

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

In this method, an element called pivot is identified and that element is fixed in its place
by moving all the elements less than that to its left and all the elements greater than that
to its right.

Shell sort
It generalized as exchanging sort, such as bubble or insertion sorting, by allowing the
comparison and exchange of elements that lie far apart.
Radix sort

In this method, sorting is done based on the place values of the number. In this scheme,
sorting is done on the less-significant digits first.

When all the numbers are sorted on a more significant digit, numbers that have the same
digit in that position but different digits in a less-significant position are already sorted on
the less-significant position.

Example program for Shell sorting


#include<stdio.h>
#include<conio.h>
int main()
{
int arr[30];
int i,j,k,tmp,num;
printf("Enter total no. of elements : ");
scanf("%d", &num);
for(k=0; k<num; k++)
{
printf("\nEnter %d number : ",k+1);
scanf("%d",&arr[k]);
}
for(i=num/2; i>0; i=i/2)
{
for(j=i; j<num; j++)
{
for(k=j-i; k>=0; k=k-i)
{
if(arr[k+i]>=arr[k])
break;
else
{
tmp=arr[k];
Page 88

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

arr[k]=arr[k+i];
arr[k+i]=tmp;
}
}
}
}
printf("\t**** Shell Sorting ****\n");
for(k=0; k<num; k++)
printf("%d\t",arr[k]);
getch();
return 0;
}

Output:
Enter total no. of elements : 7
Enter 1 number : 8
Enter 2 number : 3
Enter 3 number : 7
Enter 4 number : 9
Enter 5 number : 1
Enter 6 number : 24
Enter 7 number : 2
**** Shell Sorting ****
1 2 3 7 8 9 24
Program to example of bubble sorting
#include<stdio.h>
#include<conio.h>
#define SIZE 7
int main()
{
int i,j,temp;
int arr[ SIZE ];
for(i=0; i<SIZE; i++)
{
printf("Enter Number : ");
scanf("%d",&arr[i]);
}
for(i=0; i<SIZE ; i++)
{
Page 89

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

for(j=0; j<(SIZE-1)-i; j++)


{
if( arr[j] < arr[j+1] )
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
printf("%d\t",arr[j]);
}
getch();
return 0;
}
Output:Enter number : 6
Enter number : 3
Enter number : 7
Enter number : 1
Enter number : 4
Enter number : 5
Enter number : 2
1 2 3 4 5 6 7
Program to demonstration of selection method
#include<stdio.h>
#include<conio.h>
#define SIZE 10
int main()
{
int i,j,min,temp;
int arr[SIZE];
for(i=0; i<SIZE; i++)
{
printf("Enter element : ");
scanf("%d",&arr[i]);
}
for(i=0; i<SIZE; i++)
{
Page 90

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

min=i;
for(j=i+1; j<SIZE; j++)
if(arr[j]<arr[min])
min=j;
temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
printf("After selection sort the elements:\n");
for(i=0; i<SIZE; i++)
printf("%d\t",arr[i]);
getch();
return 0;
}
Output:Enter element : 21
Enter element : 3
Enter element : 45
Enter element : 87
Enter element : 72
Enter element : 14
Enter element : 54
Enter element : 75
Enter element : 44
Enter element : 5
After selection sort the elements :
3 5 14 21 44 45 54 72 75 87

Program for insertion sorting method


#include<stdio.h>
#include<conio.h>
int main()
{
int arr[30];
int i,j,size,tmp;
printf("\n\t------ Insertion sorting method ---------\n\n");
printf("Enter total no. of elements : ");
Page 91

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

scanf("%d", &size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d", &arr[i]);
}
for(i=0; i<size; i++)
{
for(j=i-1; j>=0; j--)
{
if(arr[j]>arr[j+1])
{
tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
else
break;
}
}
printf("\n\t------- Insertion sorted elements -------\n\n");
for(i=0; i<size; i++)
printf(" %d",arr[i]);
getch();
return 0;
}
OUTPUT
Enter total no. of elements : 7
Enter 1 number : 8
Enter 2 number : 3
Enter 3 number : 7
Enter 4 number : 9
Enter 5 number : 1
Enter 6 number : 24
Enter 7 number : 2
**** Insertion sorted elements ****
1 2 3 7 8 9 24

Program for quick sorting


Page 92

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int fst, int last);
int main()
{
int arr[30];
int i,size;
printf("Enter total no. of the elements : ");
scanf("%d",&size);
printf("Enter total %d elements : \n",size);
for(i=0; i<size; i++)
scanf("%d",&arr[i]);
qsort(arr,0,size-1);
printf("Quick sorted elements are as : \n");
for(i=0; i<size; i++)
printf("%d\t",arr[i]);
getch();
return 0;
}
void qsort(int arr[20], int fst, int last)
{
int i,j,pivot,tmp;
if(fst<last)
{
pivot=fst;
i=fst;
j=last;
while(i<j)
{
Page 93

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

while(arr[i]<=arr[pivot] && i<last)


i++;
while(arr[j]>arr[pivot])
j--;
if(i<j)
{
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
}
tmp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=tmp;
qsort(arr,fst,j-1);
qsort(arr,j+1,last);
}
}
OUTPUT
Enter total no. of elements:5
Enter total 5 elements: 7 4 2 8 1
Quick sorted elements are : 1 2 4 7 8
Program for merge sorting
#include<stdio.h>
#include<conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int main()
{
Page 94

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

int arr[30];
int i,size;
printf("\n\t------- Merge sorting method -------\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf("\n\t------- Merge sorted elements -------\n\n");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
return 0;
}
void part(int arr[],int min,int max)
{
int mid;
if(min<max)
{
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);
merge(arr,min,mid,max);
}
}
void merge(int arr[],int min,int mid,int max)
{
int tmp[30];
int i,j,k,m;
j=min;
m=mid+1;
for(i=min; j<=mid && m<=max ; i++)
{
if(arr[j]<=arr[m])
{
tmp[i]=arr[j];
j++;
Page 95

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

}
else
{
tmp[i]=arr[m];
m++;
}
}
if(j>mid)
{
for(k=m; k<=max; k++)
{
tmp[i]=arr[k];
i++;
}
}
else
{
for(k=j; k<=mid; k++)
{
tmp[i]=arr[k];
i++;
}
}
for(k=min; k<=max; k++)
arr[k]=tmp[k];
}

OUTPUT
-------Merge sorting method---------Enter the number of elements to sort: 5
Enter 1 element
: 65
Enter 2 element
: 87
Enter 3 element
: 35
Enter 4 element
: 21
Enter 5 element
: 10
------------Merge Sorted elements-----------10 21 35 65 87

Page 96

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Searching
Searching is a programming technique that determines whether an element or a data item
is present in a list or not.
There are two types of searching
1. Linear search
2. Binary search
1. Linear search:
Linear search is also referred as sequential search, is the simplest searching technique.
The search begins at one end of the list and search for the required element one by one
until the element is found or till the end of the list is reached.
The linear search technique doesnt require that the data items in the list are to be in
sorted order.
/* program to search an element using linear search*/
#include<stdio.h>
#include<conio.h>
void main()
{
int list[20];
int size;
int pos,val,i;
clrscr();
printf("\nenter the size of the list");
scanf("%d",&size);
printf("\nEnter the elements one by one:");
for(i=0;i<size;i++)
{
scanf("%d",&list[i]);
}
printf("\nEnter the value to be searched");
scanf("%d",&val);
pos=-1;
for(i=0;i<size;i++)
{
if(val==list[i])
{
pos=i;
break;
}}
Page 97

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

if(pos!=-1)
printf("\n the element is found at %d location",pos+1);
else
printf ("\n search failed");
getch();
}
2.Binary search:
The binary search algorithm is one of the most efficient searching techniques, which
requires the list to be sorted in ascending order.
To search for an element in the list, the binary search algorithm splits the list and locates
the middle element of the list.
It is then compared with the search element. If the search element is less than the middle
element, the first part of the list is searched else the second part of the list is searched.
This process continues until the search element is equal to the middle element or the list
consists of only one element that is not equal to the searching element.
/* program to search an element using binary search*/
#include<stdio.h>
#include<conio.h>
void main()
{
int first,last,middle,size,val,pos,i;
int list[20];
printf("\nenter the size of the list");
scanf("%d",&size);
printf("\nEnter the elements one by one in sorted order:");
for(i=0;i<size;i++)
scanf("%d",&list[i]);
printf("\nEnter the value to be searched");
scanf("%d",&val);
pos=-1;
first=0;
last=size-1;
while((first<=last)&&(pos==-1))
{
middle=(first+last)/2;
if(list[middle]==val)
{
Page 98

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

pos=middle;
break;
}
else if(list[middle]<val)
first=middle+1;
else
last=middle-1;
}
if(pos!=-1)
printf("\n the value found at %d position",pos+1);
else
printf("\n the value not found");
}

Matrix operation:
The program gives an idea to add two matrices.
#include<stdio.h>
#include<conio.h>
void main()
{
int r=0,c=0,j,i,matrix1[100][100],matrix2[100][100],sum[100][100];
clrscr();
printf("Enter the number of rows\n");
scanf("%d",&r);
printf("Enter the number of columns\n");
scanf("%d",&c);
printf("1st matrix values\n");
for(i=0;i<r;i++)
{
printf("Enter the elements in row %d\n",i+1);
for(j=0;j<c;j++)
scanf("%d",&matrix1[i][j]);
}
printf("2nd matrix values\n");
for(i=0;i<r;i++)
{
printf("Enter the elements in row %d\n",i+1);
Page 99

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

for(j=0;j<c;j++)
scanf("%d",&matrix2[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sum[i][j]=matrix1[i][j]+matrix2[i][j];
}
}
printf("\n1st matrix is\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",matrix1[i][j]);
}
}
printf("\n2nd matrix is\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",matrix2[i][j]);
}
}
printf("\nthe sum is\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",sum[i][j]);
}
}
getch();
}

Page 100

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Output:
Enter the number of rows
3
Enter the number of columns
3
1st matrix values
Enter the elements in row 1
1
2
3
Enter the elements in row 2
4
5
6
Enter the elements in row 3
7
8
9
2nd matrix values
Enter the elements in row 1
2
4
5
Enter the elements in row 2
1
2
1
Enter the elements in row 3
3
1
4
1st matrix is
1 2 3
4 5 6
7 8 9
2nd matrix is
Page 101

GE6151 / Computer Programming


2
1
3

4
2
1

BE(CSE) I SEM / I YEAR

5
1
4

The sum is
3 6
8
5 7
7
10 9 13
Matrix Multiplication:
#include<stdio.h>
#include<conio.h>
void main()
{
int r1,c1,r2,c2,j,i,matrix1[100][100],matrix2[100][100],mul[100][100],sum=0,k;
clrscr();
printf("Enter the number of rows of 1st matrix\n");
scanf("%d",&r1);
printf("Enter the number of columns of 1st matrix\n");
scanf("%d",&c1);
printf("Enter the number of rows of 2nd matrix\n");
scanf("%d",&r2);
printf("Enter the number of columns of 2nd matrix\n");
scanf("%d",&c2);
if(r1==c2||c1==r2)
{
printf("1st matrix values\n");
for(i=0;i<r1;i++)
{
printf("Enter the elements in row %d\n",i+1);
for(j=0;j<c1;j++)
scanf("%d",&matrix1[i][j]);
}
printf("2nd matrix values\n");
for(i=0;i<r2;i++)
{
printf("Enter the elements in row %d\n",i+1);
for(j=0;j<c2;j++)
scanf("%d",&matrix2[i][j]);
}
Page 102

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
for(k=0;k<r2;k++)
{
sum=sum+matrix1[i][k]*matrix2[k][j];
}
mul[i][j]=sum;
sum=0;
}
}
printf("\n1st matrix is\n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
{
printf("%d\t",matrix1[i][j]);
}
}
printf("\n2nd matrix is\n");
for(i=0;i<r2;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("%d\t",matrix2[i][j]);
}
}
printf("\nthe product is\n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("%d\t",mul[i][j]);
}
}
}
Page 103

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

else
{
printf("The matrices cannot be multiplied\n");
}
getch();
}

Output:

Transpose of a matrix:
#include<stdio.h>
Page 104

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

#include<conio.h>
void main()
{
int r=0,c=0,j,i,matrix[100][100],transpose[100][100];
clrscr();
printf("Enter the number of rows\n");
scanf("%d",&r);
printf("Enter the number of columns\n");
scanf("%d",&c);
printf("Enter numbers");
for(i=0;i<r;i++)
{
printf("Enter the elements in row %d\n",i+1);
for(j=0;j<c;j++)
scanf("%d",&matrix[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
transpose[j][i]=matrix[i][j];
}
}
printf("\nthe matrix is\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",matrix[i][j]);
}
}
printf("\nthe transpose matrix is\n");
for(i=0;i<c;i++)
{
printf("\n");
for(j=0;j<r;j++)
{
printf("%d\t",transpose[i][j]);
}
Page 105

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

}
getch();
}
Output:

UNIT IV
FUNCTIONS AND POINTERS
Function - definition of function - Declaration of function - Pass by value - Pass by reference Recursion - Pointers - Definition - Initialization - Pointers arithmetic - Pointers and arraysExample Problems.

Functions:

Function in programming is a segment that groups a number of program statements to


perform specific task.
A C program has at least one function main( ). Without main() function, there is
technically no C program.

Types of C functions
Basically, there are two types of functions in C on basis of whether it is defined by user or not.
Page 106

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Library function
User defined function

Library function

Library functions are the in-built function in C programming system. For example:
main()
- The execution of every C program starts from this main() function.
printf()
- prinf() is used for displaying output in C.
scanf()
- scanf() is used for taking input in C.

User defined function

C provides programmer to define their own function according to their requirement


known as user defined functions.
Every C program begins from main() and program starts executing the codes
inside main() function.
When the control of program reaches tofunction_name() inside main() function. The
control of program jumps to void function_name() and executes the codes inside it.
When, all the codes inside that user-defined function are executed, control of the program
jumps to the statement just after function_name() from where it is called.

Page 107

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Function definition
Function definition contains programming codes to perform specific task.
S yn t ax of fu n ct i on defi n i t i on
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}

Function definition has two major components:


1. Function declarator
Function declarator is the first line of function definition. When a function is invoked from
calling function, control of the program is transferred to function declarator or called function.
S yn t ax of fu n ct i on decl arat or
return_type function_name(type(1) argument(1),....,type(n) argument(n))
Syntax of function declaration and declarator are almost same except, there is no semicolon at
the end of declarator and function declarator is followed by function body.
2. Function body
Function declarator is followed by body of function which is composed of statements.
Passing arguments to functions

In programming, argument/parameter is a piece of data(constant or variable) passed from


a program to the function.
In the below example two variable, num1 and num2 are passed to function during
function call and these arguments are accepted by arguments a and b in function
definition.

Page 108

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Arguments that are passed in function call and arguments that are accepted in function
definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument variable
a should be of type int and b should be of type float,i.e., type of argument during function
call and function definition should be same.
A function can be called with or without an argument.

Return Statement

Return statement is used for returning a value from function definition to calling function.

Syntax of return statement


return (expression);
OR
return;
For example:
return;
return a;
return (a+b);
In below example, value of variable add in add() function is returned and that value is stored in
variable sum in main() function. The data type of expression in return statement should also
match the return type of function.

Page 109

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Function declaration:
Every function in C programming should be declared before they are used. These type of
declaration are also called function prototype. Function prototype gives compiler information
about function name, type of arguments to be passed and return type.
Syntax of function prototype
return_type function_name(type(1) argument(1),....,type(n) argument(n));
In the above example, int add(int a, int b); is a function prototype which provides following
information to the compiler:
1. name of the function is add()
2. return type of the function is int.
3. two arguments of type int are passed to function.
Function prototype are not needed if user-definition function is written before main()function.
Function call
Control of the program cannot be transferred to user-defined function unless it is called invoked.
Syntax of function call
function_name(argument(1),....argument(n));
In the above example, function call is made using statement add(num1,num2); frommain(). This
make the control of program jump from that statement to function definition and executes the
codes inside that function.

Page 110

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Example programs for function


Eg:1
main( )
{
message( ) ;
printf ( "\nCry, and you stop the monotony!" ) ;
}
message( )
{
printf ( "\nSmile, and the world smiles with you..." ) ;
}
Output:
Smile, and the world smiles with you...
Cry, and you stop the monotony!
Eg:2
main( )
{
printf ( "\nI am in main" ) ;
italy( ) ;
brazil( ) ;
argentina( ) ;
}
italy( )
{
printf ( "\nI am in italy" ) ;
}
brazil( )
{
printf ( "\nI am in brazil" ) ;
}
argentina( )
{
printf ( "\nI am in argentina" ) ;
}
Output
I am in main
I am in italy
I am in brazil
Page 111

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

I am in argentina
Eg:3
main( )
{
printf ( "\nI am in main" ) ;
italy( ) ;
printf ( "\nI am finally back in main" ) ;
}
italy( )
{
printf ( "\nI am in italy" ) ;
brazil( ) ;
printf ( "\nI am back in italy" ) ;
}
brazil( )
{
printf ( "\nI am in brazil" ) ;
argentina( ) ;
}
argentina( )
{
printf ( "\nI am in argentina" ) ;
}
Output:
I am in main
I am in italy
I am in brazil
I am in argentina
I am back in Italy
I am finally back in main

Depending up on their inputs (parameters) and outputs (return) functions are classified
into 4 types:
All C functions can be called either with arguments or without arguments in a C program.
These functions may or may not return values to the calling function.
1. C function with arguments (parameters) and with return value
2. C function with arguments (parameters) and without return value
Page 112

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

3. C function without arguments (parameters) and without return value


4. C function without arguments (parameters) and with return value
S.no C function

syntax

void function();
function();
without arguments and without void function()
return values
{
statements;
}

// function declaration
// function call
// function definition

void function ( int ); // function declaration


function( a );
// function call
with arguments and without void function( int a ) // function definition
return values
{
statements;
}
int function ( );
function ( );
int function( )
without arguments and with
{
return values
statements;
return a;
}

with arguments
return values

and

int function ( int );


function ( a );
int function( int a )
with
{
statements;
return a;
}

// function declaration
// function call
// function definition

// function declaration
// function call
// function definition

Note:
o
o

If the return data type of a function is void, then, it cant return any values to
the calling function.
If the return data type of the function is other than void such as int, float, double
etc, then, it can return values to the calling function.

Page 113

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

1. Example program for without arguments & without return value:


In this program, no values are passed to the function printsum() so the parameter list is
empty.
No values are returned from this function to main function so return type is void.
#include<stdio.h>
void printsum();
void main()
{
printsum();
}
void printsum()
{
printf(this is a void function);
return;
}
Output:
this is a void function
#include<stdio.h>
void printsum();
// function prototype
void main()
{
printsum();
//function call
}
void printsum() //function definition
{
int a = 50, b = 80;
printf("sum of a and b is %d, a+ b);
}
2.Example program for with arguments & without return value:
#include<stdio.h>
void printsum(int,int);
void main()
{
int a,b;
printf(enter a and b:);
Page 114

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

scanf(%d%d,&a,&b);
printsum(a,b);
printf(enter a and b again:);
scanf(%d%d,&a,&b);
printsum(a,b);
}
void printsum(intx,int y)
{
printf(sum is %d,x+y);
}
Output: enter a and b: 4 5
sum is 9
enter a and b again: 6 5
sum is 11
#include<stdio.h>
void printsum(int,int);
// function prototype
void main()
{
inta,b;
printf(enter the value of a and b);
scanf(%d%d,&a,&b);
printsum(a,b);
//function call
}
void printsum(int x, int y) //function definition
{
printf("sum of a and b is %d, x+ y);
}
3.Example program for without arguments & with return value:
#include<stdio.h>
intprintsum();
// function prototype
void main()
{
int sum;
sum=printsum();
//function call
printf("sum is %d, sum);
Page 115

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

}
int printsum() //function definition
{
inta,b,c;
printf(enter the value of a and b);
scanf(%d%d,&a,&b);
c=a+b;
return (c);
}

4. Example program for with arguments & with return value:


#include<stdio.h>
int printsum(int,int);
// function prototype
void main()
{
int a,b;
printf(enter the value of a and b);
scanf(%d%d,&a,&b);
c=printsum(a,b);
//function call
printf( sum is %d,c);
}
int printsum(int x, int y) //function definition
{
int z;
z=x+y;
return(z);
}

Pass by value:
o
o
o

In call by value method, the value of the variable is passed to the function as
parameter.
The value of the actual parameter cannot be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because,
value of actual parameter is copied to formal parameter.

Actual parameter This is the argument which is used in function call.


Page 116

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Formal parameter This is the argument which is used in function definition


#include <stdio.h>
/* function declaration goes here.*/
void swap( int p1, int p2 );
int main()
{
int a = 10;
int b = 20;
printf("Before: Value of a = %d and value of b = %d\n", a, b );
swap( a, b );
printf("After: Value of a = %d and value of b = %d\n", a, b );
}
void swap( int p1, int p2 )
{
int t;
t = p2;
p2 = p1;
p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );
}
Here is the result produced by the above example. Here the values of a and b remain unchanged
before calling swap function and after calling swap function.
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 10 and value of b = 20

Pass by reference:
o
o
o

In call by reference method, the address of the variable is passed to the function as
parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is
used by both parameters.

Page 117

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

#include <stdio.h>
/* function declaration goes here.*/
void swap( int *p1, int *p2 );
int main()
{
int a = 10;
int b = 20;
printf("Before: Value of a = %d and value of b = %d\n", a, b );
swap( &a, &b );
printf("After: Value of a = %d and value of b = %d\n", a, b );
}
void swap( int *p1, int *p2 )
{
int t;
t = *p2;
*p2 = *p1;
*p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 );
}
Here is the result produced by the above example. Here the values of a and b are changes after
calling swap function.
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 20 and value of b = 10

Recursion
A function that calls itself is known as recursive function and the process of calling function
itself is known as recursion
//recursion to find the factorial of a number
#include<stdio.h>
int fact(int)
//function prototype
void main()
Page 118

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

{
int no, factorial;
printf(enter the number);
scanf(%d,&no);
factorial=fact(no);
printf(factorial of %d is %d, no, factorial);
}
int fact(int no)
//function definition
{
if(no==1)
return 1;
else
return no*fact(no-1);
}
Output:
Enter the number 3
Factorial of 3 is 6
Classification of recursion:
Whether the function calls itself directly (i.e. direct recursion) or indirectly (i.e. indirect
recursion)
If any pending operation in return, then it is called non tail recursion. If there is no
pending operation in return, then it is called tail recursion.
According to the pattern of recursive calls(number of recursive call), recursion classified
as
a. Linear recursion it makes only one recursive call
b. Binary recursion it calls itself twice. It use the concept of binary tree
c. n-ary recursion it calls itself N times. N is not a constant number. It depends
upon the parameter.
Direct recursion:
The call for the original function is directly available in the body of the function itself.
A()
{

A(); //direct call


..
}
Page 119

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Example: direct recursion


long factorial (int x)
{
if (x == 0)
return 1;
else
return x * factorial (x 1);
}
Indirect recursion:
Indirect recursion occurs when a function calls another function, which in turn calls original
function indirectly.
It is also known as mutually recursive methods:
A()
{

B(); //function B call A()


..
}
B()
{

A(); // B() calls A() again indirectly


..
}
//indirect recursion
# include <stdio.h>
# include <conio.h>
#include <process.h>
int s=0;
void show(void);
void main()
{ if (s==5)
{
getch();
exit(0);
}
Page 120

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

show ();
}
void show ()
{
printf ("%d",s);
s++;
main();
}
OUTPUT
01234

Tail recursion:
Tail recursion is a special case of recursion in which the last operation of a function is a
recursive call.
In a tail recursive function, there are no pending operations to be performed on return
from a recursive call.

//recursion to find the factorial using tail recursion


#include<stdio.h>
int fact_tail(int, int)
//function prototype
void main()
{
int no, factorial;
printf(enter the number);
scanf(%d,&no);
factorial=fact_tail(no, 1);
printf(factorial of %d is %d, no, factorial);
}
int fact_tail(int no, int result)
//function definition
{
if(no==1)
return result;
else
return fact_tail(no-1, no * result); //there is no pending operation
}
Output:
Page 121

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Enter the number 3


Factorial of 3 is 6

Non - Tail recursion:


In a non-tail recursive function, there is a pending operation in a recursive call.
//non tail recursion to find the factorial of a number
#include<stdio.h>
int fact(int)
//function prototype
void main()
{
int no, factorial;
printf(enter the number);
scanf(%d,&no);
factorial=fact(no);
printf(factorial of %d is %d, no, factorial);
}
int fact(int no)
//function definition
{
if(no==1)
return 1;
else
return no*fact(no-1);
}
Output:
Enter the number 3
Factorial of 3 is 6

Pointers:

Pointer is a variable that holds the address of another variable or a function.


The variable might be any of the data type such as int, float, char, double, short etc.
The content of the C pointer always be a whole number i.e. address.
& symbol is used to get the address of the variable.
* Symbol is used to get the value of the variable that the pointer is pointing to.

Definition:
Consider the following statement:
Page 122

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

int quantity = 179;


This statement instructs the system to find a location for the integer variable quantity and puts
the value 179 in that location. Assume that the system has chosen the address location 5000 for
quantity. We may represent this as shown below.

During execution of the program, the system always associates the name quantity with
the address 5000. To access the value 179 we use either the name quantity or the address
5000.
Since memory addresses are simply numbers, they can be assigned to some variables
which can be stored in memory, like any other variable.
Such variables that hold memory addresses are called pointers. A pointer is, therefore,
nothing but a variable that contains an address which is a location of another variable in
memory.

Syntax
Data_type *var-name;
Ex:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
Example program
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr
ptr = &q;

*/
Page 123

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

/* display q's value using ptr variable */


printf("%d", *ptr);
return 0;
}
Output:
50

Initialization:
Pointer variables contain addresses that belong to a separate data type, which must be declared as
pointers before we use them. The declaration of the pointer variable takes the following form:
data type *pt _name;
This tells the compiler three things about the variable pt _name:
1. The asterisk(*) tells that the variable pt _name.
2. pt _name needs a memory location.
3. pt_name points to a variable of type data type.
Example:
int *p;
float *x;
Once a pointer variable has been declared, it can be made to point to a variable using an
assignment operator such as
p= &quantity;
Before a pointer is initialized it should not be used.
Ensure that the pointer variables always point to the corresponding type of data.
Example:
float a, b;
int x, *p;
p = &a;
b = *p;

This will result in erroneous output because we are trying to assign the address of a float
variable to an integer pointer.
When we declare a pointer to be of int type, the system assumes that any address that a
pointer will hold will point to an integer variable.
Assigning an absolute address to a pointer variable is prohibited. The following is wrong.
int *ptr;
Page 124

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

.
ptr = 5368;
.
.
A pointer variable can be initialized in its declaration itself. For example,
int x, *p = &x;
is perfectly valid. It declares x as an integer variable and p as a pointer variable and then
initializes p to the address of x.
The statement int *p = &x, x; is not valid.

Arithmetic operations on pointers (pointer Arithmetic)


Addition operation:
Addition of two pointers is not allowed.
We can add pointer with integer value gives destination location of pointer.
Float *ptr;
Ptr +2; //if ptr is 2000 then final value of ptr is 2000+(2*4)=2008.
Int *ptr1;
Ptr1+10; //if ptr is 2000 then final value of ptr1 is 2000+(10*2)=2020.

Increment and decrement operation:


The increment operator can be applied to an pointer type.
float *ptr;
ptr++; //if ptr is 2000 then ptr ++ is 2004
--ptr; // if ptr is 2004 then -- ptr decrements the ptr to 2000.
Subtraction operation:
Subtraction of two pointers is allowed. Pointer subtraction is meaningful only if both the
pointer point to the elements of the same array. It is used to find the number of elements
between two pointers.
Assume p1=2000 and p2 = 2008 and the array is float array.
result=p2-p1;
(2008 2004)/size of (float) =8/4=2 elements present between two pointers.

We can subtract any integer value from the pointer.


Page 125

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Float *ptr;
Ptr - 2; //if ptr is 2000 then final value of ptr is 2000-(2*4)=1992.
Int *ptr1;
Ptr1-10; //if ptr is 2000 then final value of ptr1 is 2000 -(10*2)=1980.
Relational (comparison) operation:
A pointer can be compared with a pointer of the same type. It gives Boolean value as the
result.
result =ptr1!= ptr2;
result=p1<p2;
p2=2000 result is 0;

//result =1
//if p1=2000 and p2=2004 result is 1; if p1=2004 and

resultp2==p1;
Illegal pointer operations:

//if p1=2000 and p2= 2008 then result is 0

Addition of two pointers are not allowed.


Only integers can be added to pointers. It is not valid to add a float or a double value to a
pointer.
Multiplication and division operators cannot be applied on pointers.
Bitwise operators cannot be applied on pointers.
A pointer of one type cannot be assigned to a pointer of another type (except void
pointer) .
A pointer variable cannot be assigned a non address value (except zero)

Void pointer/generic pointer:

Void pointer is a generic pointer and it can hold address of any type of object.
Void is one of the basic data types available in C .

void *ptr;
int a=10;
float b = 10.2;
ptr = &a; // ptr holds address of integer variable a
ptr =&b // ptr holds address of float variable b
Null pointer:
A Null pointer is a special pointer that does not point anywhere.
It does not hold the address of any object or function. It has numeric value 0.
Page 126

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

int *ptr=0;
int *ptr=NULL;

When a null pointer is compared with any other pointer the result is always false.
Two null pointers always compare equal.
Dereferencing a null pointer leads to a runtime error.

POINTERS AND ARRAYS


When an array is declared, the compiler allocates a base address and sufficient amount of storage
to contain all the elements of array in contiguous memory location.
The base address
is the location of the first element (index 0) of the array. The compiler also defines the array
name as a constant pointer to the first element. Suppose we declare an array x as follows:
static int x[5] = {1,2,3,4,5};
Suppose the base address of x is 1000and assuming that each integer requires two bytes, the five
elements will be stored as follows:

The name x is defined as a constant pointer pointing to the first element x[0] and therefore value
of x is 1000, the location where x[0] is stored . That is ,
x = &x[0] =1000

POINTERS IN ONE-DIMENSONAL ARRAY


main ( )
{
int *p, sum , i
static int x[5] = {5,9,6,3,7};
i = 0; p =
Page 127

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

x; sum =
0;
printf(Element Value Address \n\n);
while(i< 5)
{
printf( x[%d} %d %u\n, i, *p, p);
sum = sum + *p;
i++, p++;
}
printf(\n Sum = %d \n, sum);
printf(\n &x[0] = %u \n, &x[0]);
printf(\n p = %u \n, p);
}

Output:
Element Value Address
X[0] 5 166
X[1] 9 168
X[2] 6 170
X[3] 3 172
X[4] 7 174
Sum = 55
&x[0] = 166
p = 176

Example Problems:
Example:1
main( )
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
Page 128

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

}
OUTPUT:
Address of i = 65524
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3
Value of i = 3
Value of i = 3
Example:2
main( )
{
int radius ;
float area, perimeter ;
printf ( "\nEnter radius of a circle " ) ;
scanf ( "%d", &radius ) ;
areaperi ( radius, &area, &perimeter ) ;
printf ( "Area = %f", area ) ;
printf ( "\nPerimeter = %f", perimeter ) ;
}
areaperi ( int r, float *a, float *p )
{
*a = 3.14 * r * r ;
*p = 2 * 3.14 * r ;
}
OUTPUT:
Enter radius of a circle 5
Area = 78.500000
Perimeter = 31.400000
Example 3: SWAPPING OF TWO NUMBERS
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void swap1(int,int);
void main()
{
int a,b,c,d;
clrscr();
printf("Enter the values of a and b:= ");
scanf("%d %d",&a,&b);
Page 129

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

printf("Enter the values of c and d:= ");


scanf("%d %d",&c,&d);
printf("\n BEFORE SWAPPING : ");
printf("\n The value of a and b is : %d\t %d ",a,b);
printf("\n The value of c and d is : %d\t %d ",c,d);
printf("\n AFTER SWAPPING : ");
swap(a,b);
swap1(&c,&d);
printf("\n Method is:-Call by Value");
printf("\n **************************");
printf("\n The value of a and b is : %d\t %d",a,b);
printf("\n Method is:-Call by Address or Reference");
printf("\n ***************************");
printf("\n The value of c and d is : %d\t %d",c,d);
getch();
}
void swap(int *c,int *d)
{
int t;
t=*c;
*c=*d;
*d=t;
}
void swap1(int a,int b)
{
int t;
t=a;
a=b;
b=a;
}
OUTPUT:
Enter the values of a and b: = 2 4
Enter the values of c and d: = 6 5
BEFORE SWAPPING:
The value of a and b is: 2 4
The value of c and d is: 6 5
AFTER SWAPPING:
Method is:-Call by Value
The value of a and b is: 2 4
Method is:-Call by Address or Reference
Page 130

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

The value of c and d is: 5


UNIT V
STRUCTURES AND UNIONS
Introduction - need for structure data type - structure definition - Structure declaration - Structure
within a structure - Union - Programs using structures and Unions - Storage classes, Preprocessor
directives.

Introduction:
C Structure is a collection of different data types (heterogeneous data items) which are grouped
together under a single name and each element in a C structure is called member

Need for structure data type:


Structure deals with entities that are collection of dissimilar data types. For example, suppose
you want to store data about a book. You might want to store its name (a string), its price (a
float) and number of pages in it (an int). If data about say 3 such books is to be stored, then we
can follow two approaches:
(a) Construct individual arrays, one for storing names, another for storing prices and still
another for storing number of pages.
(b) Use a structure variable.

Structure Definition:
Unlike arrays, structure must be defined first for their format that may be used later to declare
structure variables. Let us use an example to illustrate the process of structure definition and the
creation of structure variables. Consider a book database consisting of book name, author,
number of pages, and price. We can define a structure to hold this information as follows:
struct book _bank
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of four data fields, namely title,
author, pages, and price. These fields are called structure elements or members. Each member
may belong to different type of data. book _ bank is the name of the structure and is called the
Page 131

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

structure tag. The tag name may be used subsequently to declare variables that have the tags
structure.
There are three aspects of working with structures. They are:
1. Defining a structure
2. Declaring structure variables
3. Accessing structure members
Defining a structure:
Keyword struct is used to define a structure. The keyword struct define a new datatype
which is a collection of different type of data.
The general syntax for creating a structure is,
struct structure_name
{
datatype variable1;
datatype variable2;
.
.
datatype variablen;
};
The name of the structure is known as structure tag. The variables inside the structure are known
as structure elements or members.
Eg.
struct book
{
char name[10];
int price;
int pages;
};
Here, book is the name of the structure / structure tag. name, price and pages are known as
structure elements or members.

Declaring structure variables:


Structure variables can be declared in 2 ways. They are:
a. Declaring structure variables separately
b. Declaring structure variables with structure definition
Page 132

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Declaring structure variables separately:


Eg.
struct book
{
char name[10];
int price;
int pages;
};
struct book b;
Declaring structure variables with structure definition:
Eg.
struct book
{
char name[10];
int price;
int pages;
}b;
Accessing structure members:
Structure members can be accessed by using the dot (.) operator. Dot operator is also
known as period or member access operator.
eg. b1.price=200;
(or)
scanf(%d,&price);
Structure initialization:
struct book b={computer,300,400};
(or)
b.name=computer;
b.price=300;
b.pages=400;
Example:
#include<stdio.h>
struct book
{
char name[10];
int price;
Page 133

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

int pages;
};
void main()
{
struct book b;
b.name=computer;
b.price=300;
b.pages=400;
printf(name is %s,b.name);
printf(price is %d,b.price);
printf(pages is %d,b.pages);
}
Output:
name is computer
price is 300
pages is 400
Arrays

Structures

1. An array is a collection of related 1. Structure can have elements of


data elements of same datatype.
different datatypes.
2. An array is a derived data type.

2. A structure is a programmerdefined data type.

3. Any array behaves like a built-in 3. But in the case of structure, first we
data types. All we have to do is to have to design and declare a data
declare an array variable and use it. structure before the variable of that
type are declared and used.
4.Array allocates static memory and 4.Structures allocate dynamic memory
uses index / subscript for accessing and uses (.) operator for accessing the
elements of the array.
member of a structure.

Structure within a structure (nested structure):


A structure can be nested within another structure. Nested structures are used to create
complex datatypes.
#include<stdio.h>
struct author
{
char first_name[10];
char last_name[10];
Page 134

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

};
struct book
{
char name[10];
struct author a;
int price;
int pages;
};
void main()
{
struct book b={computer,allen,weiss,300,400};
printf(name is %s,b.name);
printf(author first name is %s,b.a.first_name);
printf(author last name is %s,b.a.last_name);
printf(price is %d,b.price);
printf(pages is %d,b.pages);
}
Output:
name is computer
pages is allen
author last name is weiss
price is 300
author first name is 400
Structure as function arguments:
We can pass a structure as a function argument in similar way as we pass any other
variable or array.
#include<stdio.h>
void display(struct);
struct book
{
char name[10];
int price;
int pages;
};
void main()
{
struct book b={computer, 300,400};
display(b);
Page 135

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

}
void display(struct book b)
{
printf(name is %s,b.name);
printf(price is %d,b.price);
printf(pages is %d,b.pages);
}
Output:
name is computer
price is 300
author first name is 400
Pointer to structure:
#include<stdio.h>
struct book
{
char name[10];
int price;
int pages;
};
void main()
{
struct book b={computer, 300,400};
struct book *p=&b;
printf(name is %s,*p.name);
printf(price is %d,*p.price);
printf(pages is %d,*p.pages);
}
Output:
name is computer
price is 300
author first name is 400
typedef and structures:
The keyword typedef is used to give alias name to pre-defined datatypes like int,float as
well as to user-defined datatypes like structure.
#include<stdio.h>
typedef struct book
{
Page 136

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

char name[10];
int price;
int pages;
};
void main()
{
book b={computer, 300,400};
printf(name is %s,b.name);
printf(price is %d,b.price);
printf(pages is %d,b.pages);
}
Output:
name is computer
price is 300
author first name is 400
Example programs:
1.C program for creating student record:
#include<stdio.h>
#include<conio.h>
struct name
{
char first_name[10];
char last_name[10];
};
typedef struct student
{
int rollno;
struct name a;
int m1,m2,m3;
float percent;
};
void main()
{
student s[20];
int i,n;
printf("enter the number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
Page 137

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

printf("enter the roll no");


scanf("%d",&s[i].rollno);
printf("enter the first name ");
scanf("%s",s[i].a[i].first_name);
printf("\enter the last name ");
scanf("%s",s[i].a[i].last_name);
printf("enter the mark1");
scanf("%d",&s[i].m1);
printf("enter the mark2");
scanf("%d",&s[i].m2);
printf("enter the mark3");
scanf("%d",&s[i].m3);
s[i].percent=(s[i].m1+s[i].m2+s[i].m3)/3;
}
for(i=0;i<n;i++)
{
printf(" rollno=%d",s[i].rollno);
printf("first name=%s",s[i].a[i].first_name);
printf("last name=%s",s[i].a[i].last_name);
printf("mark1=%d",s[i].m1);
printf("mark2=%d",s[i].m2);
printf("mark3=%d",s[i].m3);
printf("percent=%f",s[i].percent);
}
}
2.C program for creating employee details:
#include <stdio.h>
struct name
{
char first_name[10];
char last_name[10];
};
typedef struct employee
{
struct name a;
int age;
char address[500];
float salary;
};
void main()
Page 138

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

{
employee e[20];
int i,n;
printf("\n enter the number of employees:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter first name:");
scanf(%s,&e[i].a[i].first_name);
printf("\nEnter last name:");
scanf(%s,&e[i].a[i].last_name);
printf("\nEnter age:");
scanf("%d",&e[i].age);
printf("\nEnter Address:");
scanf(%s,&e[i].address);
printf("\nEnter Salary:");
scanf("%f",&e[i].salary);
}
for(i=0;i<n;i++)
{
printf("First Name of the Employee : %s ", e[i].a[i].first_name);
printf("last Name of the Employee : %s ", e[i].a[i].last_name);
printf("Age of the Employee : %d ", e[i].age);
printf("Address of the Employee : %s ", e[i].address);
printf("Salary of the Employee : %f ", e[i].salary);
}
}

C Union
C Union is also like structure, i.e. collection of different data types which are grouped together.
Each element in a union is called member.

Union and structure in C are same in concepts, except allocating memory for their
members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members

Page 139

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

We can access only one member of union at a time. We cant access all member values at
the same time in union. But, structure can access all member values at the same time.
This is because; Union allocates one common storage space for all its members.
Whereas Structure allocates storage space for all its members separately.

Declare a union, initializing and accessing the members of the union.


Type

Using normal variable

Using pointer variable

union tag_name
{
data
type
var_name1; data
type
var_name2; data
type
var_name3; };

Syntax

union tag_name
{
data
type
data
type
data
type
};

Example

union student
{
int
char
float
};

Declaring
union variable

union student report;

Initializing
union variable

union student report = {100, union student rep = {100, Mani,


Mani, 99.5};
99.5};report = &rep;

Accessing
union members

report.mark
report.name
report.average

union student
{
mark; int
name[10]; char
average; float
};

var_name1;
var_name2;
var_name3;

mark;
name[10];
average;

union student *report, rep;

report
->
report
->
report -> average

mark
name

Example program for C union: // union member created inside main()


#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
Page 140

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

float percentage;
};
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name
: %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
Output:
Union record1 values example
Name
:
Subject
:
Percentage : 86.500000
Union record2 values example
Page 141

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Name
:
Mani
Subject
:
Physics
Percentage : 99.500000
Example program Another way of declaring C union:
In this program, union variable record is declared while declaring union itself as shown in
the below program.
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
}record; //member created while declaring a union
void main()
{
strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;
printf(" Name
: %s \n", record.name);
printf(" Subject : %s \n", record.subject);
printf(" Percentage : %f \n", record.percentage);
}
Output:
Name
:
Subject
:
Percentage : 86.500000
Difference between structure and union in C:
S.no C Structure

C Union

Union allocates one common storage space for all its


Structure allocates storage
members.
space for all its members
Union finds that which of its member needs high storage
separately.
space over other members and allocates that much space

Structure occupies
memory space.

We can access all members of We can access only one member of union at a time.

higher

Union occupies lower memory space over structure.

Page 142

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

structure at a time.

Structure example:
struct student
{
int mark;
char name[6];
double average;
};

Union example:
union student
{
int mark;
char name[6];
double average;
};

For above structure, memory


allocation will be like below.
int
mark

2B
char
name[6]

6B
double average 8B
Total memory allocation =
2+6+8 = 16 Bytes

For above union, only 8 bytes of memory will be allocated


since double data type will occupy maximum space of
memory
over
other
data
types.
Total memory allocation = 8 Bytes

Storage classes:
Storage class specifiers in C language tells the compiler where to store a variable, how to
store the variable, what is the initial value of the variable and life time of the variable.
Syntax: storage_specifier data_type variable _name;
There are four storage classes in C:
(a) Automatic storage class
(b) Register storage class
(c) Static storage class
(d) External storage class

S.No. Storage
Specifier

Storage
place

auto

extern

CPU
Memory
CPU
memory

static

CPU
memory

Initial
default
value
Garbage
value
Zero

Zero

/ Scope Life

local Within the function only.


Global Till the end of the main program. Variable
definition might be anywhere in the C
program
local Retains the value of the variable between
different function calls.
Page 143

GE6151 / Computer Programming


4

register

Register
memory

Garbage
value

BE(CSE) I SEM / I YEAR


local Within the function

The auto storage class:


A variable declared inside a function without any storage class specification, is by default
an automatic variable.
They are created when a function is called and are destroyed automatically when the
function exits.
Automatic variables can also be called as local variables because they are local to a
function. By default they are assigned a garbage value by the compiler.
The features of a variable defined to have an automatic storage class are as under:
Storage Memory.
Default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable is defined.
main( )
{
auto int i = 1 ;
{
{
{
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
}
The output of the above program is:
111
main( )
{
auto int i = 1 ;
{
{
auto int i = 3 ;
Page 144

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

printf ( "\n%d ", i ) ;


}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
The output of the above program would be:
321
Register Storage class:
Register variables are also local variables, but stored in register memory. Whereas auto
variables are stored in main CPU memory.
Register variables will be accessed very faster than the normal variables since they are
stored in register memory rather than main memory. But, only limited variables only can
be used as register since register size is very low. (16bits, 32 bits or 64 bits)
If register memory is full, the register variable automatically considered as auto variable.
So register variable should be declared inside a function like local variable.
Since memory is the register, We cannot use address(&) operator in the register variable.
The features of a variable defined to be of register storage class are as under:
Storage - CPU registers.
Default initial value - Garbage value.
Scope - Local to the block in which the variable is defined.
Life - Till the control remains within the block in which the variable is defined.
#include<stdio.h>
void main()
{
int a,b;
register int c;
printf("Enter a : ");
scanf("%d",&a);
printf("Enter b : ");
scanf("%d",&b);
c= a+b;
printf("Sum of Numbers : %d",c);
}
Output:
Enter a : 2
Enter b : 3
Page 145

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

Sum of Numbers : 5
Static storage class:
Static variables have static (global) life time.
It will be stored in main memory.
It will take both in the local scope and global scope
Its initialized automatically by 0 for static int type and 0.0 for static float type and \0
for char.
If static variable is present inside the local scope, the variable is initialized only once.
The features of a variable defined to have a static storage class are as under:
Storage Memory.
Default initial value Zero.
Scope Local to the block in which the variable is defined.
Life Value of the variable persists between different function calls.

#include<stdio.h>
void fun();
void main(){
int i=0;
for(i=0;i<3;i++)
{
fun();
}
}
void fun()
{
static int a=10;
int b=20;
printf(a = %d,a);
printf(++a = %d,++a);
printf(b = %d,b);
printf(++b = %d,++b);
}
Output:
a =10
++a = 11
b=20
++b=21
a =11
Page 146

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

++a = 12
b = 20
++b =21
difference between the automatic and static storage classes.
The extern storage class:

A variable that is declared outside any function (i.e. before main function) is by default
an external variable. External variables are also known as global variables.
Global variables remain available throughout the entire program.
The extern storage class specifier cannot be used in the parameter declaration either in the
function declaration or function definition.

The features of a variable whose storage class has been defined as external are as follows:
Storage Memory.
Default initial value Zero.
Scope Global.
Life As long as the programs execution doesnt come to an end.
Eg:
#include<stdio.h>
int num = 75 ;
void display();
void main()
{
printf("Num : %d",num);
display();
}
void display()
{
printf("Num : %d",num);
}
Output:
Num :75
Num :75
Eg:
int i ;
main( )
Page 147

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

{
printf ( "\ni = %d", i ) ;
increment( ) ;
increment( ) ;
decrement( ) ;
decrement( ) ;
}
increment( )
{
i=i+1;
printf ( "\non incrementing i = %d", i ) ;
}
decrement( )
{
i=i-1;
printf ( "\non decrementing i = %d", i ) ;
}
The output would be:
i=0
on incrementing i = 1
on incrementing i = 2
on decrementing i = 1
on decrementing i = 0

Pre-processor directives:
Translators convert a high level language program into an equivalent machine level
language program. Compiler is not the only translator that works before the execution of a
program.
The preprocessor is another translator that works and processes the source code before it
is given to the compiler. It operates under the control of commands known as preprocessor
directives.
The preprocessor is used to include the header files, macro expansions, conditional
compilation, and line control.
The important points for writing a pre-processor directives are as follows:
1. The pound symbol (#) should be the first character in a source file.
2. A new-line character ends the pre-processor directive.
3. The preprocessor directives can appear anywhere in a program but are generally placed at
the beginning of a program before the main function.
Page 148

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

The various preprocessor directives available in C language are as follows:


1. Macro replacement directive (#define,#undef)
2. Source file inclusion directive (#include)
3. Line directive (#line)
4. Error directive(#error)
5. Pragma directive(#pragma)
6. Conditional compilation directives (#if,#else,#elif,#endif,#ifdef,#ifndef)
7. Null directive(# new-line)
1.Macro replacement directive:
a.#define:
A macro is a facility provided by the C pre-processor ,by which a token can be replaced
by the user-defined sequence of characters. Macros are defined with the help of define directive.
The identifier name immediately following the define directive is called the macro name. There
are 2 types of macros:
1.Macro without arguments, also called object-like macros:
Syntax:#define macroname replacement-list
#include<stdio.h>
#define pi 3.14
void main(){
int rad=5;
float c;
c=pi*r*r;
printf(c=%f,c);
}
2.Macro with arguments, also called function-like macros:
Syntax:#define macroname(parameter-list) replacement-list
#include<stdio.h>
#define sqr(x) (x*x)
void main(){
int side=5;
int c;
c=sqr(side);
printf(c=%d,c);
}
Page 149

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

b.#undef:
The undef pre-processor directive causes the specified identifier to be no longer defined
as a macro-name.
Syntax: #undef identifier
#include<stdio.h>
#define pi 3.14
#undef pi
void main(){
int rad=5;
float c;
c=pi*r*r;
printf(c=%f,c);
}
Output:
Compilation error undefined symbol pi
2.Source file inclusion directive:
It tells the preprocessor to replace the directive with the content of the file specified in the
directive. it is used to include the header files, which contains the prototypes of the library
functions.
eg. #include<stdio.h>
3.line directive:
The line directive is used to reset the line number and the file name as reported by
_ _LINE_ _ and _ _FILE_ _ macros.
#include<stdio.h>
void main(){
printf(line no is %d, file name is %s,_ _LINE_ _,_ _FILE_ _);
#line 200
printf(line no is %d, file name is %s,_ _LINE_ _,_ _FILE_ _);
#line 100 abc.c
printf(line no is %d, file name is %s,_ _LINE_ _,_ _FILE_ _);
}
Output:
line no is 4, file name is line.c
line no is 200, file name is line.c
line no is 100, file name is abc.c

Page 150

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

4.error directive:
The error directive causes the preprocessor to generate the customized diagnostic
message and causes the compilation to fail.
#include<stdio.h>
#error this is a customized error
void main(){
printf(hi);
}
Output:
Compilation error
Fatal error.c 2:error directive: this is a customized error
5.pragma directive:
The pragma directive is used to specify the diverse options to the compiler.
Syntax: #pragma token-sequence
Some of the options are:
option
role
-C
Allow nested comments
-CDoes not allow nested comments
-r
Enables the use of register variables
-rSuppresses the use of register variables
#include<stdio.h>
#pragma option -C
void main(){
/*start of outer comment
/*inner comment*/
end of outer comment*/
printf(pragma);
}
Output:pragma
Note:If pragma directive is not used it will show an error.
6.Conditional compilation directive:
Conditional compilation means that a part of a program is compiled only if a certain
condition comes out to be true. Some of the Conditional compilation directives are #if, #ifdef,
#elif,#endif,#else.
#include<stdio.h>
Page 151

GE6151 / Computer Programming

BE(CSE) I SEM / I YEAR

#define NUM 11
void main(){
#if((NUM%2)==0)
printf("\nNumber is Even");
#else
printf("\nNumber is Odd");
#endif
}
Output:
Number is odd
7.Null directive:
The null preprocessor directive is a single number sign (#) alone on a line. It has no
effect.
#include <stdio.h>
#
void main(){
puts("Hello, world!");
}
Output: Hello, world!

Page 152

You might also like