0% found this document useful (0 votes)
2 views

Programming in C and Numerical Analysis

This document introduces algorithms and flowcharts, essential tools for programming, detailing the structure of a computer, including its components like the processor, memory, and input/output devices. It explains the importance of algorithms, their characteristics, and provides examples of flowcharts for various problems. Additionally, it discusses the advantages and limitations of flowcharts in programming.

Uploaded by

vikky.kumar0070
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Programming in C and Numerical Analysis

This document introduces algorithms and flowcharts, essential tools for programming, detailing the structure of a computer, including its components like the processor, memory, and input/output devices. It explains the importance of algorithms, their characteristics, and provides examples of flowcharts for various problems. Additionally, it discusses the advantages and limitations of flowcharts in programming.

Uploaded by

vikky.kumar0070
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 251

CHAPTER – I Remarks

ALGORITHMS AND FLOWCHARTS


1.0 STRUCTURE
1.1 Introduction
1.2 Objective
1.3 Programmer’s Model of a Computer
1.4 Algorithm
1.5 Flowchart
1.1 INTRODUCTION
The modern age computers come in many different forms, they are massive, multipurpose
main-frames, super-computer, and desktop-size personal computers to laptop computers.
Programming language is based on flowchart and algorithm which is main tool of language. Good
programmer always makes first flowcharts then starts the programming for completing knowledge
about the logic and error finding is easy.
1.2 OBJECTIVE
At the end of this chapter the students should be able to
 Know about programming model of a computer
 Know about writing various types of algorithm
 To convert algorithm to a flowchart
1.3 PROGRAMMER’S MODEL OF A COMPUTER
The three main components of modern digital are
(i) Processor
(ii) Memory
(iii) Input and output devices
1.3.1 Processor
The processor is the computing engine of the computer. It executes the sequence of instructions
i.e., the programs. It is the brain of the computer and is also known as the central processing unit
(CPU). It has two constituents.
(a) Control unit
(b) Arithmetic and logic unit (ALU)
1.3.2 Control Unit :
The control unit serves the purpose of controlling the execution of instructions by providing
timing control signals. This unit contains logic and timing circuits that generate the appropriate
signals necessary to execute each instruction in a program. The control unit works by fetching an
instruction from memory. The instruction which is in some form of binary code is then decoded by
the logic circuitry in the control unit to determine the proper format of the instruction. The control
unit then sends various control signals to different parts of the computer to execute the specified
operation. Thus, the control unit is as vital in a computer system as the nervous system is in our body.
1.3.3 Arithmetic and Logic Unit :
Besides control unit, the computer system has an arithmetic and logic unit. The various arithmetic
and logical operations such as addition, subtraction, comparison, etc. are performed in this unit.
2 Programming in C and Numerical Analysis

Remarks
Primary Memory Secondary
Memory
RAM ROM

Mouse Memory System Monitor

Control Unit Output


Input Devices
Devices

Central Processing
Arithmetic
Unit
and logic unit

Keyboard Printer

Block Diagram of a Computer


1.3.4 Memory :
A computer must have a place for holding the instructions (known as programs) and data on
which the program will operate. The place which is used for this purpose is called memory. The
memory is divided into locations, such as bytes and words and these locations are identified by their
addresses. A memory operation is used to read or write one memory unit. In a read operation, the
processor provides the address and receives the data read from the addressed location while in a write
operation, data is written at the particular address. Memory is of two types :
(a) Primary memory
(b) Secondary memory
1.3.4.1 Primary Memory : The memory which is always available to the processor is called the
primary memory or the main memory. This memory is made up of magnetic cores or semiconductor
circuits and is respectively called core memory or semi-conductor memory. It is further divided into
two types:
(i) RAM : RAM or Random Access Memory is a volatile memory available to the processor. All the
instructions and data required for a program execution are in it. Its contents are erased as soon as the
power is turned off. It is a read/write memory. Data can be read as well as written on it. Its contents
can be altered.
Algorithms and Flowcharts 3

(ii) ROM : ROM or Read Only Memory is non-volatile memory available to the processor. All the Remarks
information regarding the functioning of the computer is stored in it. Its contents are non-volatile and
cannot be altered once written. As its name suggests, data can only be read from it. It is supplied by
the manufacturer and contains information about the functioning of the processor.
1.3.4.2 Secondary Memory : Primary memory is limited in size and storage. Many times it happens
that the data and programs are large enough to be stored in the main memory. The instructions and
data are then stored in the secondary memory or auxiliary memory. Some standard storage devices are
hard disks, floppy disks, magnetic tapes, CD-ROMs, magnetic drums, etc. It is a non-volatile
memory. Programs, data or any other information kept in secondary storage devices can be easily
transferred to the primary memory.
1.3.5 Input and Output Devices
Input devices are used to input data which is then processed and the output is then returned
through an output device. Thus, input and output devices act as the inter face between the computer
and the outside environment. These interfaces allow the exchange of information between the
computer and the external world. Some standard input/output devices are keyboard, monitor, printer,
mouse, speaker, joystick etc.
(a) Keyboard : It is a standard input device which resembles a typewriter. It contains keys for
inputting alphabets, digits and special characters. Some special keys are also provided to perform
predefined functions. It is one of the most popular input device and forms a part of a standard
computer.
(b) Mouse : Mouse is another popular input device which is a sort of pointing and picking tool. It is a
point and pick choices from the computer. A mouse consists of two or three buttons.
(c) Monitor : Monitor or screen is a standard output device. A monitor may be mono-chrome or
coloured. All the data and information processed by the computer are displayed on the monitor.
(d) Printer : It is an output device which is used to print the contents of a file or output of a program.
Printers are of various types depending on the printing mechanisms. eg., dot matrix, inkjet printers,
laser printers etc.
1.3.6 Compiler :
Compilation is the task of translating text written in a computer language (source language) into
another computer language. The original sequence is usually called the source code and the output
called object code. Commonly, the output has a form suitable for processing by other programs.
Compilation is primarily used for translating source code from a high level language to a lower
level language.
1.3.7 Interpreter :
An interpreter translates high level instructions into a intermediate form, which it then executes.
Compilation is faster than interpretation since it takes the whole program as input to compile it,
whereas an interpreter takes one line at a time and interprets it. However, there is no need for
compilation stage during interpretation since an interpreter can immediately execute high level
programs after translating them into an intermediate form.
1.4 ALGORITHM
An algorithm is described as “a complete, clear finite number of logical steps for solving a
specified problem”. The word algorithm is derived from the name of a 9 th century Arab
mathematician, Al-Khowarizmi, who developed the methods for solving problems which used
specific step by step instructions. An algorithm contains a finite number of steps each of which may
4 Programming in C and Numerical Analysis

Remarks include a number of operations. Besides accomplishing its objectives, an algorithm must have certain
characteristics which are as follows :
(i) It is simple to understand step by step solution of the problem.
(ii) It is easy to debug, that is, errors can be easily pointed out.
(iii) It is independent of programming languages.
(iv) Time taken by each step must be finite and small.
(v) The algorithm cannot open ended and the process always end after a finite number of steps.
(vi) Easy to coded into its equivalent in high level language.
Example 1 : Write an algorithm to find the sum of two numbers.
Solution : In this problem, two numbers are given. Their sum is to be calculated and then displayed.
The steps of the algorithm are :
1. Input first number as a.
2. Input second number as b.
3. Calculate their sum as c = a + b, where c is another number in which their sum is stored.
4. Display c.
5. Terminate the process.
Example 2 : Write an algorithm to find greatest among three numbers.
Solution : In this problem, three numbers a, b and c are given. The greatest number among them is to
be determined and displayed. The steps of the algorithm are :
1. Input numbers a, b and c.
2. If a  b then greater = a else greater = b.
3. If greater  c then greatest = greater else greatest = c.
4. Display greatest.
5. Terminate the process.
Example 3 : Write an algorithm to find the circumference of a circle with radius r.
Solution : In this problem, radius r of a circle is given. The circumference of the circle is to be
computed by the formula 2r. The steps of the algorithm are :
1. Input the radius r of the circle.
2. Calculate the circumference of the circle by using the formula c = 2r, where  is a constant.
3. Display c.
4. Terminate the process.
Example 4 : Write an algorithm for factorial computation.
Solution : In this problem, the number whose factorial is to be calculated is given. Its factorial is to be
computed and displayed. The steps of the algorithm are :
1. Input number N.
2. Set fact = 1.
3. If N =0 then fact = 1.
4. Set K = 1.
5. Repeat step 6 for K = 1 to N.
6. fact = K*fact.
7. Display fact.
8. Terminate the process.
1.5 FLOWCHART
A flowchart is a visual or graphical representation of an algorithm. It is the pictorial
representation of the steps involved in solving a problem. It employs a series of symbols and arrows,
Algorithms and Flowcharts 5

each of which represents a particular operation or step in an algorithm. For easy visual recognition, a Remarks
standard convention is used so that every computer programmer interprets a flowchart in the same
manner.
Following are standard shapes for specified operations.
Symbol Name Meaning

Terminal Oval is used for two purposes, to define the starting


point and ending point of a program.

Input/Output Parallelogram is used for input/output.

Process Rectangle is used to indicate processing. It


Represents calculations, data manipulation
or information processing often as a single
algorithmic step.

Decision Diamond-shaped box is the decision box. It


has one entry point and at least two exit points generally
for “yes” and “no” depending upon the decision taken
inside the box. The box represents a comparison,
question or decision that determines alternative paths to
be followed.
1.5.1 Advantages of flow charts are :
(i) It is easy to detect an error with the help of flowchart.
(ii) It allows the problem-solver to break the problem into parts. These parts can be connected to
make a master-chart
(iii) It is the pictorial representation of the program steps, so it facilities easier checking of an
algorithm.
(iv) It is the blue-print of the logic to solve any problem. Before coding begins, it assists the
programmer to determine the type of logic control to be used in a program.
(v) It is a good way of communication with other users. Also it is a compact way of representing
an algorithmic solution to a problem.
(vi) It is a permanent record of the solution, which can be consulted at a later time. It serves as a
guiding document for program writing or coding.
1.5.2 Limitations of flow charts are :
(i) There are no standards which specify the detail that should be included in any
flowchart.
(ii) There is a possibility to make errors while drawing flow charts.
(iii) It is very difficult to include any new step in the existing flowchart. Redrawing of the flowchart is
the only alternative, which is also difficult and time consuming.
(iv) Drawing of flowcharts is a very tedious process.
(v) If an algorithm has complex loops and branches, its flowchart is quite difficult to draw.
(vi) Some times flowchart can not be as detailed as desired.
6 Programming in C and Numerical Analysis

There are three fundamental operations that normally constitute a flowchart for solving a problem.
These logic structures are used in the flowchart to represent any construct of programming language.
These logic structures are :
Remarks 1. Sequence 2. Selection 3. Iteration
1.5.3 Type – I (Sequence flow Chart) :
In a sequential flow, the operations flow from one action to the other. Instructions are processed
in a sequence.
Example 1 : Draw a flowchart to find sum of two numbers.
Solution :
START

Input X

Input Y

Z=X+Y

STOP

Example 2 : Draw a flowchart to find the circumference of a circle.


Solution :
START

Input radius r of the circle

Calculate Circumference
c = 2**r

Print circumference c

STOP
Algorithms and Flowcharts 7

1.5.4 Type – II (Selection flow chart) :


Remarks
A diamond-shaped decision box is used for branching the flow of program. Depending on the
answer to the question contained in the box, the flow follows from one of the outgoing paths. Thus
selection refers to selecting a path to follow in a flowchart.
Example 3: Draw a flow chart to find root of quadratic equation.
STARTT

Input coefficients of quadratic equation

Read a, b, c

Disc = b2 4ac

Is Yes root1 = b/2a


Disc=0?
root2 = b/2a

Is
Disc>0?
Yes
disc) / 2a

 disc / 2a Print “real roots are root1, root2”

Print “Imaginary roots r1 + ir2 and r1ir2”

STARTT
8 Programming in C and Numerical Analysis

Example 4 : Draw a flowchart to find the greatest among three numbers.


Remarks
Solution :

START

Input the numeric values of a, b and c

Yes If No
a>b

Yes If No No If Yes
a>c b>c

Print a is the greatest Print c is the greatest Print b is the greatest

STOP

1.5.5 Type – III (Iteration flow chart) :


Algorithms and Flowcharts 9

In iteration, a set of operations can be performed repeatedly depending on a test condition. The
flow comes out of this loop only when the condition is not satisfied. This repetition (or looping) is
among the most important tools available to a computer programmer. Readers will learn about
selection and iteration in subsequent chapters.
Example 5 : Draw a flowchart for factorial computation. Remarks
Solution :

START

Input N

Fact = 1

If No If No Fact = Fact*N
N= 0? N= 1?

Yes Yes N=N 1

Print Fact

STOP
10 Programming in C and Numerical Analysis

Example 6 : Draw a flowchart for gcd of a and b.


Remarks
Solution :

START

Input a and b

No If No If Yes
a 0 b 0

Yes

Temp = b
b=a
If
No Yes
b divides
a

Temp = Remainder when a is divided by b.


a=b
b = temp b is gcd of a and b

STOP
Algorithms and Flowcharts 11

Example 7 : Draw a flowchart to check whether a number is Prime or not.


Solution : Remarks

START

Input a positive integer

Read n

Is Yes
Print “Number is prime”
n=2

No

i=1

Is No Print “Number is prime”


i<n

Is Yes Print “Number is prime”


n%
i=0

STOP
i=i+1
12 Programming in C and Numerical Analysis

Remarks Exercise 1.1


1. What do you understand by programmer’s model of a computer ? How does it help in problem
solving and programming ? Illustrate.
2. What is an algorithm ? What are its merits and demerits ?
3. What is a flowchart ? List its use and write its types, advantages and limitations.
4. How does a flowchart differ from an algorithm ?
5. Write an algorithm to find perimeter of a circle and ask the user to input radius x.
6. Draw a flow chart and write an algorithm to find the roots of a quadratic equation.
7. Write an algorithm to find square of a number.
8. Write an algorithm to find the weekday of a particular date entered by the user using a calendar.
9. Write an algorithm and draw a flowchart to find whether the number entered by the user is odd or
even.
10. Write an algorithm for checking a square matrix for symmetry.
11. Draw a flowchart to find cube of a number.
12. Draw a flowchart to find smallest of given set of numbers in an array.
13. Draw a flowchart to find the surface area and volume of a sphere.

Keywords :
CPU, ALU, Primary memory, Secondary memory, RAM, ROM, Algorithm, Flowchart.
Summary
In this unit we study about programming model of computer, various types of algorithms and
flowcharts with the help of suitable examples.
Remarks
CHAPTER – II
INTRODUCTION TO ‘C’ AND DATA TYPES
2.0 STRUCTURE
2.1 Introduction
2.2 Objective
2.3 Importance of C
2.4 The C-Character Set
2.5. C - Tokens
2.6 Data Types
2.7 Constants
2.8 Qualifiers
2.9 User defined data types
2.10 The printf Function
2.11 Escape Sequence (Backslash Character Constants)
2.12 Scanf Function
2.13 The Use of Comments
2.14 The #include<stdio.h> Directive
2.15 The Main Function
2.16 A Typical C Program
2.17 Execution of a C Program
2.1 INTRODUCTION
C is a programming language developed at AT and T’s Bell Laboratories of USA in 1972. It was
designed and written by Dennis Ritchie. C is a general purpose, structured programming language. Its
instructions consists of terms that resemble algebraic expressions, supported by certain English
keywords such as if, else, for, do and while.
2.2 OBJECTIVE
At the end of this chapter students should be able to
 Various type of characters (keyword, constants, variable)
 Knowledge about various types of data types
 Use of printf and scanf statement
 Use of comments
 Starting of C programs
2.3 IMPORTANCE OF C
C is a popular programming language due to its various qualities. The main characteristics of C
language are given below :
1. The programs written in C language are very concise as it has a large number of operations
included within the language.
2. It provides rich and large set of built-in functions, operators and data types that can be used to
write any complex program. So programs written C are very concise.
3. C language is more reliable, simple and easy to use.
4. C programs are highly portable, as compared to other-high-level languages. This means that C
programs written on one computer can be run on another with little or no alternation.
5. C language is format free language.
6. C is a structured programming language. A programmer can break a problem into function
modules or blocks.
7. C allows users to write additional library functions of their own.
14 Programming in C and Numerical Analysis

Remarks 2.4 THE C-CHARACTER SET


2.4.1 Alphabets :
A B C D……..X Y Z
a b c d e……...x y z
2.4.2 Digits :
0 1 2 3 ….. 8 9

2.4.3 Special Characters


, comma ’ apostrophe _ underscore
. period ” quotation mark $ dollar sign
; semicolon ! exclamation mark % percent sign
: colon < opening angle bracket & ampersand
# number sign (or less than sign) ^ caret
? question mark > closing angle bracket ~ tilde
| vertical bar (or greater than sign) * asterisk
/ slash ( left parenthesis ) right parenthesis
\ backslash [ left bracket ] right bracket
 minus sign { left bracket } right bracket
+ plus sign.
2.4.4 White Space Characters
Blank space Horizontal tab
Carriage return New line
Vertical tab Form feed
2.4.5 Trigraph Characters
Many keyboards may not support all the characters that belong to the C-character set. Therefore,
C provides a way for users to enter characters not available on some keyboards by providing the
concept of “trigraph” sequences. Each trigraph sequence consists of three characters which are two
question marks followed by another character.

Trigraph Sequence Translated Character


?? / ^caret
??  ~ tilde
?? = # number sign
?? ( [ left bracket
?? ) ] right bracket
?? < { left brace
?? > } right brace

2.5. C - TOKENS
The smallest individual unit in a C program are known as C-tokens. C programs consist of tokens
put together according to the syntax of the C programming language. C has six types of tokens as
shown in the following figure:
Introduction to ‘C’ and Data Types 15

Remarks
C - Tokens

Keywords Identifiers Constants Special Operators Strings


Symbols

2.5.1 Identifiers
Identifiers are used for naming program elements, i.e., variables, constants, functions, arrays, etc.
These are defined by the user. The identifiers should be given relevant and meaningful names so that
the programs can be easily understood.
2.5.2 Variables
Variable is a data-item whose value can change during the execution of program. If at a particular
instant of time it has a value say 9, it may have another value say 15 at any other instant of time.
However, a variable storing integers must hold an integer at all times. When we declare a variable, we
create a particular storage in the memory. The scope of a variable refers to the portion of program in
which it can be used.
The difference between variables and constants is that, in a variable the content of the memory
location may change i.e., value of the data item may change, however in the case of a constant the
value remains fixed and cannot be changed.
2.5.2.1 Rules for Naming a Variable or Identifier
The various rules for naming a variables are as follows :
1. Variable names must begin with a letter of the alphabet. In C, the underscore character( _ ) is
considered a letter.
2. The first character can be followed by any number of letters or digits from 0 through 9.
3. Blank space, period, semi-colon, comma or slash and all such special characters are not permitted
in variable names.
4. C compiler is case sensitive. Therefore, the variable names RAM, Ram and ram are all regarded
as three separate variables in C.
5. Keywords cannot be used as variables names.
6. On most computers, only the first seven or eight characters are used to identify a variable. No
other variable used in the program should begin with the same seven or eight characters. For
example, the names variable_1 and variable_2 cannot be distinguished by such compilers.
2.5.3 Keywords
There are certain reserved words, called keywords, that have standard predefined meaning in C.
These keywords can be used only for their intended purpose and they cannot be used as programmer-
defined identifiers.
The standard key words are :
auto do goto signed unsigned
break double if sizeof void
case else int static volatile
char enum long struct while
const extern register switch continue
float return typedef default for
16 Programming in C and Numerical Analysis

short union
Remarks Example 1 : Determine which of the following are valid identifiers. If invalid, explain why?
(a) 1deepak :- Invalid – first character should be alphabet.
(b) name :- Valid.
(c) name and address : - Invalid  should not contain space.
(d) name&address :- Invalid – should not contain special character symbol.
(e) return :- Invalid – should not be keyword.
(f) file-3 :- Valid.
Example 2 : Assume that your version of C can recognize only the first 8 characters of an identifier
name, through identifier names may be arbitrarily long. Which of the following pairs of identifier
names are considered to be identical and which are distinct?
(a) name, names  distinct
(b) list1, list2  distinct
(c) identifier_1, identifier_2  same
2.6 DATA TYPES
A data type is defined as a finite set of values along with a set of rules for permissible operations
applicable on the entity. The various data types in C language are :
2.6.1 Primitive (Fundamental) data types :
(a) Integer (int)
(b) Character (char)
(c) Floating point number (float)
(d) Double
(e) Void
2.6.2 Derived data types :
(a) Arrays
(b) Structures
(c) Unions
(d) Functions
(e) Pointers
2.6.3 User-defined data types :
(a) Type def
(b) Enum
2.6.1 (a) Int (Integers) :
Integers are the most commonly used data type in C. Integers are used for all arithmetic and
logical operations. The integers in C are declared as :
int x;
int y, z;
int w = 20;
The statements declare integer variables x, y, z and w which can store integer values. The integer
variables can be initialized (assigned some initial value) at the declaration time. The third statement
initializes the integer variable w to value 20.
The range of int as 32768 to 32767 and 2 bytes memory space is required.
2.6.1 (b) Char (Character) :
The type char is used to store a single character of information. Char is the actual name of the
data type, and must be written as such in the declaration. The word character cannot be substituted. A
Introduction to ‘C’ and Data Types 17

variable of char type can be initialized by enclosing a single character (alphabet, digit, special
character, etc.) within single quotes.
The character variables are declared in C as : Remarks
char c;
char d, e;
char name = ‘K’;
The statements declare character variables c, d, e and name which can store a single character of
information. The character variables can also be initialized at the declaration time. The third statement
initializes the character variable name to character ‘K’. It’s range from 128 to 127 and it needs 1 byte
of memory requirement.
2.6.1(c) Floating Point Type
Floating point numbers are numbers having a decimal point. The compiler differentiates between
floating-point numbers and integers because they are stored differently in the computer. Floating point
numbers have a greater range and can express decimal number, therefore they are sometimes referred
to as real numbers. Some examples are 10.575, 900.18, 126.9. The major differences between
integers and floating point numbers can be summed up as follows :
1. Integers include only whole numbers while real numbers can be either whole or fractional i.e.
they have a decimal point.
2. Floating point numbers can represent a much broader range of numbers. Their range depends
upon the computer.
3. Floating point operations are usually slower in execution and often occupy more memory than
integer operations.
4. Floating point numbers sometimes can lead to loss of mathematical precision. The result may be
slightly rounded off (as we can see that 3.6 can be represented as 3.59999 or 3.600019 in floating
point), where integers are always exact.
5. Both are stored in different formats, internally. Integers are stored as ordinary binary numbers
while floating point numbers are stored into two parts – a fractional part (called the mantissa) and
an exponent part. Both part are stored in binary form.
The floating point variables are declared in C as
float x;
float length, breadth;
float z = 110.08;
These statements declare floating point variables x, length, breadth and z which can store floating
point values. Sometimes floating point number in scientific notation. For example 10256.55 can
be written as 0.1025655105 or 0.1025655E05. The letter E (or e) stands for the word exponent.
The exponent is the integer and the number before e is called mantissa. The value of mantissa lies
between 0 and 1.
2.6.1 (d) Double Type Numbers :
Whenever the accuracy obtained by using a variable of type float is insufficient for the purpose at
hand, it can be declared to be of the type “double” instead of being of type “float”. The type “double”
provides about twice the number of significant digits for the result, otherwise, it is quite similar to
type “float”. The exact number of significant figures varies from system to system but generally a
float variable has 7 digits, a double variable has 16 or 17 digits.
Numbers of types float and double are treated identically by the system in terms of calculation.
All floating point numbers are converted into double values automatically whenever they are used in
any operation.
18 Programming in C and Numerical Analysis

Using the type “float” saves memory as a float variable takes up only half as much space as a
double. To display a double value, the format characters %f (for standard floating-point notation) or
%e (for scientific or exponential notation) are used, similar to as used with type “float”.
The double variables are declared in C as :
Remarks double d;
double root1, root2;
double z = 120.42;
The statement declare double variables d, root1, root2, and z which can store double precision
values.
2.6.1 (e) Void Type :
The void type is a generic type with no value. It is generally used to specify the type of the
functions. The type of a function is said to be void when it does not return any value to the calling
function. Void can also play the role of a generic type, such that it can be used to represent any of the
other standard types like int, char, float, double etc.
2.7 CONSTANTS
There are four basic types of constants in C. These are :

Constants

Numeric ConstantsCharacter Constants

IntegerRealSingle Character String


ConstantsConstants ConstantsConstants

2.7.1 Numeric Constants


Integers and floating-point constants represent numbers. They are often referred collectively as
numeric type constants.
Integer Constants
An Integer constant is an integer-values number. Thus, it refers to a sequence of digits.
The following rules apply to the integer constants :
1. Integer constants must have atleast one digit.
2. Commas and blanks cannot be included within the constant.
3. It should not contain decimal point and exponent.
4. The constant can be preceded by a minus () sign and plus (+) sign. Default sign in +.
5. The value of a constant cannot exceed specified minimum and maximum bounds. For each type
of constant, these bounds will vary from one C compiler to another. For a 16 bit computer, the
allowable range for an integer constant is -32768 to 32767.
Integer constants can be written in three different number systems : decimal (base 10), octal (base
8) and hexadecimal (base 16).
Introduction to ‘C’ and Data Types 19

Decimal Integer Constant


A decimal integer constant can consist of any combination of digits taken from the set 0 to 9. If
the constant contains two or more digits, the first digit must be something other than 0, like
0, 130, 210, 153, 32767, 32768, +78
Octal Integer Constant Remarks
An octal integer constant can consist of any combination of digits taken from the set 0 to 7.
However, the first digit must be 0, in order to identify the constant as octal number. Some examples
of octal integers are
0, 047, 0723
Hexadecimal Integer Constant
A sequence of digits beginning with 0x or 0X is considered as a hexadecimal integer. It can then
be followed by any combination of digits taken from the sets 0 to 9 and a to f (either uppercase or
lower case). The letter a to f (or A to F) represent the decimal numbers 10 to 15.
Some valid hexadecimal constants are
0x 0X2 0Xabcd 0x9F
The magnitude of an integer constant can range from zero to some maximum value that varies
from computer to computer. A typical maximum value for must computers is 32,767 on 16-bit
machines and 2,147,483,647 on 32 bit machines.
Invalid Integer Constants
The following are some examples of invalid integer constants :
(i) 32,156  contains comma
(ii) 32156.0 contains a decimal point
(iii) 32e9  contains an exponent
(iv)   should contain atleast one digit.
Real-Constants
A real or floating point is a base 10 number that contains either a decimal point or an exponent or
both. For example,
5000.0 0.0083 0.75 0.1667E08 0.15E02
The following rules apply to all real constants :
(a) A real constant must have atleast one digit.
(b) It must have a decimal point.
(c) It can either be positive or negative.
(d) If no sign precedes it, it is assumed to be positive.
The exponent form consists of two parts : mantissa and exponent. These can be used to represent
the values of constants that are either too small or too big. For example, the real constant 1.6667E + 8
has a mantissa value of 1.6667 and an exponent +8 which is equivalent to 1.6667  10 8. The
magnitude of floating point constant ranges from 3.4E38 to 3.4E + 38 on 16 bit machine.
The following rules apply to real constants represented in exponential form :
(a) The mantissa part and exponential part should be separated by letter e.
(b) The default sign of mantissa part is positive.
(c) The exponent must have atleast one digit, which should be a positive or negative integer.
(d) The range of real constants expressed in exponential from is from 3.4e 38 to 3.4e 38 for 16-bit
computers.
Invalid Real Constants
The following are some examples of invalid real constants :
(i) 20,125.0  contains comma.
(ii) 25325  does not contain decimal point.
20 Programming in C and Numerical Analysis

(iii) 253e13.2  exponent should be an integer.


2.7.2 Character Constants
A character constant is a single alphabet, a single digit or a single special symbol enclosed within
single quotation marks (inverted commas).
Remarks Some character constants are :
‘A’, ‘5’, ‘3’, ‘.’ ‘?’
Character constants have integer values that are machine dependent. Thus, integer values
representing the character may be different on different machines. The constants themselves are
independent of the character set. This feature eliminates the dependence of a program on any
particular character set (like ASCII or EBCDIC).
String Constants
A string constant consists of any number of consecutive characters (including whitespace
characters) enclosed in double quotation marks.
For example :
“green”, “Hello”, “$ 18.90”, “WELL DONE”, “X”.
Sometimes special characters may also be included as a part of a string constant. These characters
must be represented in terms of their escape sequences which are discussed in next article.
At the end of every string constant, the C compiler automatically adds a null character (\0) as the
last character of the string. This character is not visible when the string is displayed. However, by
searching for the null character, end of every string can be identified easily.
Example 1 : Determine which of the following numerical values are valid constants. If a constant is
valid, specify whether it is integer or real. Also, specify the base for each valid integer constant.
(a) 0.6  Valid real
(b) 12345  Valid  Decimal integer
(c) 0516  Valid  Octal integer
(d) 27,822  Invalid  Comma is not allowed
(e) 013DE  Valid  Hexadecimal
(f) 0.8E08  Valid  Float
(g) 1.2 E0.8  Invalid  Exponent cannot float.
2.8 QUALIFIERS
Qualifiers are used to extend the range of numbers.
2.8.1 Qualifiers associated with int
(1) long
It declaration is long int x;
or some computer as long x;
It increases the range of int from (32768 to 32767) to (2,147,483,648 to 2,147,483,647). Int uses
16 bits and now long int uses 32 bits.
(2) unsigned
It’s declaration is unsigned int x;
or some computer as unsigned x;
Thus convert the range int from (32,768 to 32,767) to (0 to 65535). But int and unsigned int both
uses 16 bits of size.
(3) short int
It’s declaration is short int x;
This decrease the range of int from (32,768 to 32,767) to (128 to 127). It uses 8 bits in size.
(4) signed int
It is same as int. It’s declaration is signed int x;
Introduction to ‘C’ and Data Types 21

2.8.2 Quantifiers used for char


(1) unsigned char
It’s declaration is unsigned char x;
The change in range of char from (128 to 127) to (0 to 255). It use 8 bits as char used. Remarks
(2) signed char
It is same as char. It’s declaration is signed char x;
2.8.3 Quantifiers used for float
(1) double
It’s another data type of float which increases the range of float from (3.4E38 to
3.4E +38) to (1.7E 308 to 1.7E 308). It uses the 64 bits whereas float uses 32 bits. It’s declaration is
double x;
(2) long double
It increases the range of double from (1.7E 308 to 1.7E +308) to (3.4E 4932 to 1.1E +4932). It
uses 80 bits whereas double uses 64 bits. It’s declaration is long double x;

Integer Character

signed unsigned
int unsigned int char
short int unsigned short int signed char
long int unsigned long int unsigned char

Fig. Primary Data Types


Floating-Point Type
void

float double long double

Type Size(bits) Range


char or signed char 8 128 to 127
unsigned char 8 0 to 255
int or signed int 16 32768 to 32767
unsigned int 16 0 to 65535
Shot int or signed short int 8 128 to 127
unsigned short int 8 0 to 255
long int or signed long int 32 2,147,483,648 to 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
22 Programming in C and Numerical Analysis

float 32 3.4E 38 to 3.4E +38


double 64 1.7E 308 to 1.7E + 308
long double 80 3.4E 4932 to 1.1E +4932

Remarks Example 1 : Write appropriate declaration for each group of variables.


(a) float point variables : root1, root2
(b) long integer variables : counter
(c) short integer variable : index
(d) double precision number : tax, net.
Solution : (a) float root1, root2;
(b) long counter;
(c) short int index;
(d) double tax, net;
2.9 USER DEFINED DATA TYPES
In C, we can define an identifier for representing an existing data type. It is known as “type
definition” and can be used for declaration of variables. The syntax for type definition is given
below : typedef type identifier;
Here, type represents an existing data type and identifier represents the new name in place of
type. Remember that typedef is not capable of creating any new data type but provides only an
alternative name to an existing data type. For example
typedef int number;
typede float amount;
After the above declarations, the compiler will recognize number as an alternative to int and
amount to float. Now, the variables can be created using number and amount as given below :
number num1, num2;
amount fund, loan, installment;
typedef is often used to declare structure and array types. This definition is useful for
documentation.
C provides another user-defined data type known as “enumerated data type”. It attaches names to
numbers, thereby increases the readability of the program. It is generally used when we know in
advance the finite set of values that a data type can have. The syntax for enumerated data type is given
below :
enum tag {member1, member2,…, memberm);
Here, enum is a required keyword tag is a name that identifies enumerations having this
composition, and member1, member2,…, memberm are the individual identifiers that may be
assigned to variable of this type (as given below). The member names must differ from each other,
and they must be distinct from other identifiers whose scope is same as that of the enum ration.
After enumeration definition, corresponding enumeration variables can be declared as :
enum tag var1, var2, ….., varn;
Here var1, var2, …, var n are enumeration variables of type tag.
The enumberation definition can be combined with the variable declarations, as given below :
enum tag {member1, member2, ……, member m} var1, var2, …., varn;
The tag is optional in this situation.
For example,
Introduction to ‘C’ and Data Types 23

enum mar_status {single, married, divorced, widowed);


enum mar_status person1, person2;
Enumerated variables are generally used to clarify the operation of a program.
Remarks
2.10 THE PRINTF FUNCTION
The printf function is used to output or print a message, either on screen or on paper. This
function can be used to output any combination of numerical values, single characters and strings
(The letter “f” in printf could stand for either “formatted” or “function”). The main purpose of the
printf function is to move data from computer’s memory to the standard output device. In general
terms, the printf function is written as,
printf (“control string”, arg1, arg2, …., argn);
where control string refers to the string or data that has to be printed. It also includes formatting
information for the variables present in the output data stream. The arguments may be constant, single
variable or array names or more complex functions. arg1, arg2,….,argn are the arguments that
represent the individual output data items. Consider the following examples :
printf(“Welcome to the wonderful world of C programming”);
The following simple character string is printed as an output,
Welcome to the wonderful world of C programming
The character string to be printed is a series of characters starting and ending with double
quotation marks. These punctuation marks signify the starting and ending of the control string or in
other words, it serves to delimit it. Whenever it is needed to include double quotes as part of a string,
it must be preceded by a backslash (\).
e.g. printf(“My name is \ “Sumit\” “);
More examples on printf( )
int x = 5, y = 8;
printf( “The value of x = %d”, x);
printf( “\nThe value of y = %d and x = %d”, y, x);
Then output
The value of x = 5
The value of y = 8 and x = 5.
Conversion Meaning
Character
%c Data is displayed as a single character.
%d Data item is displayed as a signed integer.
%e Data item is displayed as a floating-point value with an exponent in
scientific notation.
%f Data item is displayed as a floating-point value without exponent.
%s Data item is displayed as a string.
%i Data item is displayed as signed integer.
%u Data item is displayed as an unsigned integer.
%g Data item is displayed as a floating-point value using either –etype or
type conversion depending on value. Trailing zeros and trailing
24 Programming in C and Numerical Analysis

decimal point will not be displayed.


%o Data item is displayed as an octal integer, without a leading zero.
%x Data item is displayed as a hexadecimal integer without the leading
0x.

Remarks The following example illustrates various conversion specifications. There is nothing difficult
about these conversions, but a certain amount of attention to detail is required.
printf( “Case 1 : %d : \n”, 356); /* shows an integer */
printf( “Case 2 : %c : \n”, ‘A’); /* shows a character */
printf( “Case 3 : %d \n”, 356); /* equivalent to the above */
printf( “Case 4 : 2d : \n”, 356); /* also defaults to the width of number as above */
printf( “Case 5 : %9d : \n”, 356); /* right justified in a field of 9 */
printf( “Case 6 : %8d : \n”, 356); /* left-justified in a field of 8 */
printf( “Case 7 : %8d : \n”,  356); /*negative number right justified in a field of 8 */
printf( “Case 8 : %f : \n”, 123.356); /* prints in float format with 6 decimal digits */
printf( “Case 9 : %e : \n”, 987.664); /* prints in “e” format */
printf( “Case 10 : %8.2f : \n”, 987.664); /* prints in “f” format with 2 decimal places (rounded) in
a field of 8 columns */
printf( “Case 11 : %12.3e : \n”, 987.664); /* prints in “e” format in a field of 12 with 3 decimal
places */
printf( “Case 12 : %s : \n”, “Algebra”) ; /* prints a string */

Output
Case 1 : 356:
Case 2 : A :
Case 3 : 356 :
Case 4 : 356 :
Case 5 : 356 :
Case 6 : 356 :
Case 7 : 356 :
Case 8 : 123.356000 :
Case 9 : 9.876640E+02 :
Case 10 : 987.66 :
Case 11 : 9.876E+02 :
Case 12 : Algebra :

2.11 ESCAPE SEQUENCE (BACKSLASH CHARACTER CONSTANTS)


C supports some special backslash character constants that are used in output functions. These are
used to express certain non-printing characters as well as the backslash ( \ ) and the apostrophe (’).
Introduction to ‘C’ and Data Types 25

For example, a line feed (LF), referred to as a newline in C, can be represented as ‘\n’. Such escape
sequences always represent single characters, even though they are written in terms of two or more
characters.

Some commonly used backslash character constants are listed below :

Escape Sequence Meaning (character) ASCII value Remarks


\a bell(alert) 007
\b backspace 008
\f formfeed 012
\n newline (line feed) 010
\r carriage return 013
\t horizontal tab 009
\v vertical tab 011
\” quotation mark(”) 034
\’ apostrophe( ’ ) 039
\? question mark (?) 063
\\ backslash ( \ ) 092
\0 null 000

2.11.1 The New Line Character

The new line character is equivalent to the type-writers carriage return, which advances the output
to the beginning of the next line. The printf function does not print subsequent information in the next
line automatically.
printf (“This example demonstrates”);
printf(“the importance of new line character.”);
printf(“\n Now the statement starts from next line.”);
The output for these statements will be
This example demonstrates the importance of newline character.
Now the statement starts from next line.

2.12 SCANF FUNCTION


The syntax of scanf( ) function is
scanf(“format specification string”, list of variable addresses);
Format specification string consists of conversion character %, a data type character or type
specifier and an optional number specifying the field width. The variable names following it are
preceded by ampersand symbol (&) to specify the variable’s addresses. An example of scanf( )
function is
scanf(“%d %f”, &a, &b);
This function accepts an integer value for variable a and a float value for variable b from the user. The
variable a and b should have been previously declared as integer and float variables respectively.

2.13 THE USE OF COMMENTS


26 Programming in C and Numerical Analysis

Consider the following statement


printf(“Hello world”); /* It prints Hello world */
In this statement the fragment
“/* It prints Hello world */”
is a comment in the program which is used to describe the program. The comments are not processed
by the compiler and are used to make the program more readable. Comments are used so that
Remarks whenever the programmer wants to recall the program, he can easily do so. Comments starts with “/*”
and end with “*/”. Anything in between these two symbols is considered as comment and is not
processed by the compiler.
The format of the comment is /* comment text */.
Comments cannot be nested. For example,
/ * This example demonstrates / * Hello world * / * /
is invalid.
A comment can be split over more than one line. For example,
/* This example demonstrates importance of new line character.
Now the comment starts from next line */

2.14 THE #include<stdio.h> DIRECTIVE


The #include directive is a preprocessor directive which is used to include the file stdio.h into the
program. The file stdio.h is a header file which contains functions that perform input-output
operations such as printf, scanf. By including the file stdio.h, we can use its functions in our program.
In general, a statement that begins with the sign # called as the hash or pound sign in known as the
preprocessor directive. The various other header files such as “conio.h”, “math.h”, containing several
useful functions can be included in our program by using the directives #include <conio.h> and
#include<math.h> and so.

2.15 THE MAIN FUNCTION


The main function is a special function and must be present in every program. Whenever a C
program is run, it is the first function to be executed. It calls all other functions in the program
according to the flow of the program. Consider the following program.

void main ()
{
printf(“Enter the wonderful world of C programming”);
printf(“\n Hello world”) /* It prints Hello world */
}

In the above block void is the return status that main( ) function returns to the operating system.
The main( ) function can return any data type and if any return type is not specified it implicitly
returns int. In case, there is no value returned to system using return statement, it resulting in warning.
To avoid this we use void main ( ).
The main function in the above example contains two printf statements and a comment enclosed
in curly braces “{” and “}”. During the execution of program, the program control is passed first to
Introduction to ‘C’ and Data Types 27

main function after the opening brace “{”. The two printf functions are then called turn-wise and on
encountering the closing brace “}” the main function ( ) ends. Every statement in a program is ended
with a semi-colon. The semi-colon is a statement terminator.

2.16 A TYPICAL C PROGRAM Remarks

A typical C program contains preprocessor directives, a main function ( ), optional user defined
functions according to program flow, symbolic constants and variables which can be used in main
function ( ) or other functions. Comments are used to make program descriptive and user readable.

An overview of a basic C program is given below :


#include <stdio.h> /* Preprocessor directives */
void main ( ) /* Start of main function */
{
………………………
………………………
/* Set of statements */
………………………
printf(“…………..”) /* Printf statement */
………………………
………………………
} /* End of main function */

Let us take a beginner step in understanding and using C by demonstrating the above structure
using an actual C program. The program given below is quiet basic and is only for reader’s
clarification. Actually, the complexity of C program is defined by programmer’s skill, understanding
and usage required.

Program
#include <stdio.h> /* start program */
void main ( )
{ printf(“Hello world”); /* Printf statement */
printf(“I am here”);
}

Output
Hello world
I am here

2.17 EXECUTION OF A C PROGRAM

A C program is executed in a series of steps. These are :


28 Programming in C and Numerical Analysis

(i) Creating the program.


(ii) Compiling and linking the programming
(iii) Executing the program.

Remarks 2.17.1 Creating the program

Once we have loaded the Editor window in the Turbo C++ IDE, the program is ready to receive
the program. The source code or program must be entered into a file. The file name may consist of
leters, digits and special characters, followed by extension .c.
Examples of valid file name are
hello.c
DDE.c
Ba.c
when the editing is over, the file is saved on the disk. The file can now be referred any time later
by its file name.

2.17.2 Compiling and linking the program

Once the program has been created, it is then compiled. During compilation, the source program
is translated into a form suitable for execution by the computer. If the source program is correct, the
compilation will display successful result and the translated program is started in another file having
extension .o (in Unix) or .obj (in MS-DOS). This program is called the object code.
If there are errors in the syntax and semantics of the program, then these errors are listed by the
compiler and the compilation is not completed. The errors should be corrected in the source program
with the help of the editor and the compilation is not a success till all the errors are eliminated.
Linking is the process of putting together all program files and functions required by the program.
For example, the header file “stdio.h” may be linked to the main program. The compiled and linked
program is called the executable object code and is stored automatically in another file with
extension .out (in Unix) or .exe(in MS-DOS).

2.17.3 Executing the program

Executing is a trivial task now. Simply run the .out or .exe file. This loads the executable object
code into the memory and the program is executed. Depending on the logic of the program, the
program may request the user to input data, which is fed through the keyboard. If the program does
not provide the desired result, then it may be due to incorrect logic used in the program code.
To rectify it, the program code is re-written and the entire process of creating,
compiling, linking and execution is repeated till the program produces the desired or acceptable
output.
Introduction to ‘C’ and Data Types 29

The above process is illustrated in the following flowchart :


Remarks
START

Create the source program

Store it in a file with extension .c

Compile the program

Are there syntax errors Yes Rectify the errors

No
Link the program

Are there linking errors Yes

No

Execute the program

Are there run time or logic errors


Yes

No

Display result

STOP
30 Programming in C and Numerical Analysis

Remarks Exercise 2.1

1. What are constants? Name and describe the four basic types of constants in C.
2. Summarize the rules that apply to all numeric type constants.
3. What do you mean by data types. What are various data types used in C language? Illustrate their
declaration and usage?
4. Describe the process of computation and compilation of a source program in C.
5. Explain with examples the syntax of scanf( ) and printf( ) functions.

Keywords
int , float, double, long, char, printf, scanf, stdio.h, conio.h

Summary

In this chapter we studied about various type of data types and their uses with the help of
suitable example. We also studied uses of printf and scanf.
Remarks

CHAPTER – III
OPERATORS AND EXPRESSIONS

3.1 INTRODUCTION
C includes a large number of operators which fall into several different categories. An operator is
a symbol that tells the computer to perform certain mathematical or logical task. Operators are used in
programs to perform operations on data and variables. They usually form a part of the arithmetic or
logical expressions.
The data items that operators act upon are called operands. Some operators requires two operands,
while others act upon only one operand. A few operators permit only single variables or constants as
operands. The C operators can be classified into a number of categories. They include following :
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
An expression is combination of operators and operands. It is formed according to the syntax of
the language. For example,
a+b=5
x  y = 10.5
15 < 10
a+=b
are all expressions.
3.2 OBJECTIVE
At the end of this chapter students should be able to
 Use of various types of operator
 Use of Associativity
 Use of Priority
 Use of various types functions in math.h

3.3 ARITHMETIC OPERATORS


Arithmetic operators are used to perform arithmetic operations on data. There are five arithmetic
operators in C, viz.
Operator Purpose
+ Addition
 Subtraction
* Multiplication
/ Division
% Modulo division
The operands acted upon by arithmetic operators must represent numeric values. Thus, the
operands can be integer quantities, floating-point quantities or characters (having a corresponding
numeric value). The modulo division (%) requires that both operands be integers and the second
32 Programming in C and Numerical Analysis
Remarks
operand be non-zero. Division by 0 results in an error. The modulo division cannot be used on
floating point data. Also, the division operator ( / ) requires that the second operand be non-zero.
Integer division truncates any fractional part (i.e., the decimal part of the result is dropped), while
in a floating point division, the result is a floating point number.
3.3.1 Integer Arithmetic
When both the operands of an arithmetic expression are integers, the expression is called an
integer expression and the operation is called integer arithmetic. Integer arithmetic always yields an
integer as a result. Suppose that a and b are two integers whose values are 7 and 2 respectively.
Several arithmetic expression involving these values are :
a+b=9
ab=5
a * b = 14
a/b=3 (decimal part truncated)
a % b = 1 (remainder of division)

a b a/b a%b
5 3 1 2
5 3 1 2
5 3 1 2
5 3 1 2
Note : (i) sign of a % b depends only upon a
(ii) a = ((a / b)*b) + (a % b)
3.3.2 Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. Since floating point
values are rounded to the number of significant figures permitted, the final value is an approximation
of the correct result. There is no certainity that the final value calculated is correct and accurate. It will
always be an approximation.
Suppose that x and y are two floating-point variables whose values are 12.5 and 2.0 respectively.
Then, we will have :
x + y = 14.5
x  y = 10.5
x * y = 25.0
x / y = 6.25
Finally, suppose that v1 and v2 are character-type variables representing the characters P and T,
respectively. P is encoded as 80, T is encoded as 84 in ASCII character set. Then, we have
v1 = 80
v1 + v2 = 164
v1 + v2 + 9 = 173
v1 + v2 + ‘9’ = 221
During integer division, if both the operands are of same sign, the result is truncated towards zero.
That is
8/9=0 and 4/5=0
However, if one of them is negative, the direction of truncation is machine dependent. That is 4/5
may be 0 or 1.

11.2.3 Precedence Arithmetic Operators Remarks


Operators and Expressions 33

Priority Operators Description Associativity


1st () Parentheses R  L (Right to left)
2nd */% Multiplication, Division, L  R (Left to right)
Modular division
3rd + Addition, Subtraction LR
4 th = Assignment RL

Example 1: Determine the value each of the following expression


int i = 8, j = 5, c = 3, d = 4;
float x = 0.005, y = 0.01;
char e = ‘e’, j = ‘j’
(i) (i  3 * j) % (c + 2 * d) / (x  y)
Solution :
= (8 – 3 * 5) % (3 + 2 * 4) / (0.005 (0.01))
Parenthesis solved R  L
= (8 – 15) % (3 + 8) / (0.015)
= 7 % 11 / 0.015
= 7 / 0.15 =  466.666667
(ii) (3 * i  2 * j) % (2 * e  f)
Solution :
= (3 * 8  2 * 5) % (2 * 101  102)
= (24  10) % (202  102)
= 14 % 100 = 14
(iii) 2 * ((i / 5) + (4 * (j  3)) % (i + j  2))
Solution :
= 2 * ((8 / 5) + (4 * (5 – 3)) % (8 + 5 – 2))
= 2 *(1 + ( 4 * 2) % 11)
= 2 * (1 + 8 % 11) = 2 * (1 + 8) = 2 * 9 = 18.
11.3 RELATIONAL OPERATORS
Relational operators are symbols that are used to test the relationship between two variables or
between a variable and a constant. C has six relational operators, defined as follows :
Operator Meaning
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== equal to
!= not equal to
(either greater than or less than)
Notice that some of these operators consist of only one character whereas other contain two.
Those with two characters must not contain spaces between them, otherwise it result in an error. The
value of a relational operator is either true or false. For example,
5 < 10 is true
but 15 < 10 is false.
When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results compared.
Note : The assignment operator ‘=’ should not be confused with the relational operator ‘==’. The
former is used to assign the value on its right to the variable on its left. Whereas, the latter is
used to compare the values on its two sides.
Remarks 11.3.1 Precedence of Relational Operators
34 Programming in C and Numerical Analysis

Priority Operators Description Associativity


1st < <= Less than, Less than LR
> >= or equal to, greater than,
Greater than or equal to
2nd == != Equal to, not equal to LR

11.3.2 Combined precedence table for arithmetic operators and relational operators

Priority Operators Associativity


1st () RL
2nd *, / , % LR
3rd +, LR
4th <, < =, >, > = LR
5th = =, ! = LR
6th = RL

Example 2 : Determine the value of each of the following expressions :


int i = 8, j = 5;
float x = 0.005, y =  0.01;
char c = ‘c’, d = ‘d’;
(i) i < = j
Solution : 8 < = 5 false
(ii) c > d
Solution : ‘c’ > ‘d’  99 > 100  false
(iii) x > = 0
Solution : 0.005 > = 0  true

(iv) x < y
Solution : 0.005 <  0.01  false
(v) ((i + j) < = (c + d))
Solution : ((8 + 5) < = (99 + 100))
 (13 < = 199)  true
11.4 LOGICAL OPERATORS
The logical AND and OR operators combine conditional expressions to form a new complex
expression. The logical NOT operator is a unary operator that operates on a single expression (either
simple or complex). Following are the symbols corresponding to the logical operators :
Operator Meaning
! logical NOT (unary operatory)
|| logical OR
&& logical AND
The logical operators && and | | are used to test more than one condition and make decisions. For
example,
a + b > c &&c > 10 ;
An expression of this kind which combines two or more relational expressions, is termed as a
logical expression or a compound relational expression. Logical expressions also yield either a value
true or false.
The logical negation of expression ‘E’ is Remarks
Operators and Expressions 35

0 if E is non-zero
1 if E is 0
The logical OR of two expression is true if either of them is true. Otherwise it is false. Thus, a | | b
is true if a is true or b is true.
The logical AND of two expression is true if both of them are true. Otherwise it is false. Thus, a
&& b is true if a is true and b is true.
a b a||b a && b !a
F F F F T
F T T F T
T F T F F
T T T T F

11.4.1 Precedence of Logical Operators


Priority Operators Description Associativity
1st ! Logical NOT RL
2nd && Logical AND LR
3rd || Logical OR LR

11.4.2 Combine precedence of Arithmetic, relational and logical operators

Priority Operators Associativity


1st () RL
2nd ! RL
3rd *, /, % LR
4th +,  LR
5th >, <, >=, <= LR
6th = =, ! = LR
7th && LR
8th || LR

Example 3 : Determine the value of each the following expressions


int i = 8, j = 5;
float x = 0.005, y =  0.01;
char c = ‘c’, d = ‘d’
Solution : (i) (i > 0) && (j < 5)
 (T) && (F)  F
(ii) (i > 0) | | (j < 5)
 (T) | | (F)  T
(iii) (x > y) && (c > 0) | | (j < 5)
 (T) && (T) | | (F)
 (T) | | (F)  (T)
(iv) (x > y) | | (i > 0) && (j > 5)
 (T) | | (T) && (F)
 (T) | | (F)  (T)
(v) ! (i < = j)
 ! (8 < = 5)
 ! (F) = T
Remarks 11.5 BITWISE OPERATORS
36 Programming in C and Numerical Analysis

Some applications require the manipulation of individual bits within a word of memory. C
contains several special operators that allow such bitwise operations to be carried out easily and
efficiently. These operators are used for testing the bits, or shifting them left or right. Bitwise
operators should not be applied to float or double numbers. Some bitwise operators are :
Operator Meaning
~ complement (unary operator)
& bitwise AND
| bitwise OR
^ bitwise XOR
<< shift left
>> shift right
As discussed earlier, all data is stored in memory in the binary format (using 0’s and 1’s). The
bitwise operators manipulate each and every bit of the binary equivalent of its operands. In other
words, to perform the operation a & b, the corresponding bits of a and b are ‘anded’ to obtain the
result.
The following are the rules for bitwise operations :
a b ~a a|b a&b a^b
0 0 1 0 0 0
0 1 1 1 0 1
1 0 0 1 0 1
1 1 0 1 1 0

For the shift operation, to shift a binary number by n bits towards left/right, each of its bits is
moved by n positions in left/right direction.
The use of bitwise operators can be better understood with the following example:
Consider
int x = 73, y = 14;
8 bit Binary equaivalent of 73 is 01001001 and 14 is 00001110.
For ~x, all the bits of its binary representation are complemented. The result is 10110110, which
is the representation of 182. Thus ~x = 182.
For x & y, x | y and x ^ y, the respective operation is performed between corresponding bits of x
and y, i.e.,
0 1 0 0 1 0 0 1
& 0 0 0 0 1 1 1 0
__________________________
0 0 0 0 1 0 0 0 [Binary equivalent of 8]

0 1 0 0 1 0 0 1
| 0 0 0 0 1 1 1 0
__________________________
0 1 0 0 1 1 1 1 [Binary equivalent of 79]

0 1 0 0 1 0 0 1
^ 0 0 0 0 1 1 1 0
__________________________
0 1 0 0 0 1 1 1 [Binary equivalent of 71]
Therefore,
x & y = 8,
Remarks
x | y = 79
Operators and Expressions 37

and x ^ y = 71.
For x << 3, each bit is shifted towards left by 3 bit positions. The three leftmost bits are discarded
and an equal number of zeros are added towards the right.
The result is 01001000 which is the binary equivalent of 72.
Therefore, x << 3 = 72.
Similarly, the result of y >> 1 is 00000111 which is the binary equivalent of 7.
Therefore, y >> 1 = 7
Note : Here, the bitwise operators are explained using 8 bit representation. When executing programs,
the bitwise operations are performed on all bits that are used for storing the operands. For
instance, if an integer is stored in 2 bytes, then to perform the operation a & b, where a and b
are two integers, all the corresponding 16 bits of a and b are “anded”.
11.6 ASSIGNMENT OPERATORS
Assignment operators are used to assign the result of an expression to a variable. We have earlier
used the assignment operator ‘=’. In addition, there are several different ‘short hand’ assignment
operators in C known as compound assignment operators.
Statement Meaning
a+=b a=a+b
a=b a=ab
a*=b a=a*b
a/=b a=a/b
a%=b a=a%b
a|=b a=a|b
a^=b a=a^b
a << = b a = a << b
a >> = b a = a >> b
For example,
x + = 5;
On executing this statement, 5 is added to x i.e. it is equivalent to x = x + 5. Thus, the abbreviated
version is more compact. It also compiles faster, thereby saving computer time.
Another advantage of the assignment operator is that it is similar to the human thought process.
Also, whatever appears on the left hand side need not be repeated. For example, consider the
statement
a = a + a + 5;
We can write
a + = a + 5;
However, only one of the occurrence of a is eliminated and therefore one a still appears on the
right hand side.
All the assignment operators have the same priority and are associated from right to left.
11.7 INCREMENT AND DECREMENT OPERATORS
The operation of adding and subtracting 1 from a variable occurs so frequently in programming
that C provides two very useful operators generally not found in other languages. These are the
increment and decrement operators
++ and  
The operator ++ adds 1 to the operand, while   subtracts 1.
Both are unary operators and have the following form :
++m; or m++;
 m; or m ;
The position of the operator does affect the value of the operand when they are used in
expressions on the right hand side of an assignment statement. For an independent statement ++m and
38 Programming in C and Numerical Analysis

Remarks m++ mean the same thing. However, expression ++m (pre-increment) increments first the value of m
and then it assigns the incremented value to the assignment variable. On the other hand expression m+
+ (post-increment) first assigns the current value of m to the variable and then increments the value of
m. For example,
Statement Value of m Value of x
m = 8; 8 
x = ++m; (pre-fix) 9 9
x = m++; (post-fix) 10 9
In pre-increment operator, first the value of m is incremented by 1 to become 9 and then this
value 9 is assigned to the variable x. While in post-increment, first the value of m(9) is assigned to
variable x, so x becomes 9 and then the value of m is incremented. So the final values of x and m are
9 and 10 respectively.
11.8 CONDITIONAL OPERATOR (TERNARY OPERATOR)
A ternary operator pair “? :” is available in C to construct conditional expressions of the form
test expression ? exp1 : exp2
During the usage of the conditional operator the test expression is evaluated first. Based on its
value, either exp1 or exp2 are evaluated to return the result of the conditional expression. Only one of
the embedded expression exp1 or exp2 is evaluated to determine the value of the conditional
expression. If the evaluation of test expression is true, then exp1 is evaluated and this becomes the
value of the conditional expression. However, if the test expression is false (i.e., its value is zero),
then exp2 is evaluated and its value becomes the value of the conditional expression. For example,
consider the following statements :
a = 15;
b = 9;
x = (a < b) ? b : a;
In this example, the test expression is (a < b) which is evaluated first and it has the value 0 (false).
Thus, x is assigned the value of exp2 i.e., a.
Therefore, x = 15
11.9 SPECIAL OPERATORS
C supports some special operators of interest such as unary minus operator, comma operator,
sezeof operator, pointer operators (& and *) and member selection operators (. And >). Moreover
there are two preprocessor operators known as “stringizing” (#) and “token pasting” (##) operators.
The unary minus, comma and sizeof operators will be discussed in this section while the remaining
operators will be discussed in subsequent chapters.
11.9.1 The Unary Minus Operator
It is the most common unary operation, where a numerical constant, variable or expression is
preceded by a minus sign. In C, all numeric constants are positive. So, a negative number is actually
an expression, consisting of the unary minus operator, followed by a positive numeric constant.
However, unary minus operator is different from the subtraction operator. The unary minus operator
is a unary operator so it takes only one operand and just negates its value, whereas subtraction
operator is binary operator and needs two operands.
11.9.2 The Comma Operator
The comma operator can be used to link the related expressions together. In a comma linked list,
the expressions are evaluated from left to right and the value of the right-most expression becomes the
value of the combined expression. For example, the statement
val = (x = 9, y = 7, x  y);
Operators and Expressions 39

first assigns the value 9 to x, then assigns 7 to y and finally assigns (9 – 7) to val. Comma operator has Remarks
the lowest precedence of all operators, so the parentheses are necessary.
Some applications of the comma operator are :
In for loop :
for (i = 1, j = 10; i < 10; i++, j )
In while loop :
while (c = getchar( ), c! = ‘S’)
In exchanging values :
t = x, x = y, y = t;
In Function calls :
Consider the function call
func1(i, (j = 1, j + 4), k);
It calls func1 with three arguments, not four. The arguments are i, 5, k.
Note : The comma operator separates the elements of a function argument list. Mixing of the two uses
of comma is legal but you must use parentheses to distinguish them.
11.9.3 The sizeof Operator
The sizeof operator is a unary operator that returns the size of its operand, in bytes. The word
sizeof always precedes its operand. The operand may be an expression, or it may be a constant.
The general form of sizeof operator is
sizeof (operand)
Elementary programs rarely make use of the sizeof operator. However, this operator allows the
determination of the number of bytes allocated to various types of data items. This information can be
very useful when transferring a program to a different computer or to a new version of C. It is also
used for dynamic memory allocation.
11.9.4 Operator Precedence
Every operator in C has a precedence associated with it. It helps in the correct evaluation of an
expression involving more than one operator. There are distinct levels of precedence and operator
belonging to the higher level of precedence is evaluated first. The operators which belong to the same
precedence level are evaluated either from “left to right” or from “right to left” depending on the
Associativity of the operator. A complete list of operators, their precedence and their rules of
association are provided in the following table. The groups are listed in the order of decreasing
precedence.
For example, consider the statement
y = x + 10 && z  5;

Operators Operator Summary Associativity


Precedence Group
()[] function array, structure member RL
pointer to structure member
 ++   ! ~ * & unary operators RL
sizeof (type)
*/% arithmetic multiply, divide and LR
modulo division
+ arithmetic add and subtract LR
<< >> bitwise shift operators LR
> < >= <= relational operators LR
== != equality operators LR
& bitwise AND LR
^ bitwise XOR LR
40 Programming in C and Numerical Analysis

Remarks | bitwise OR LR


&& logical AND LR
|| logical OR LR
?: conditional operator RL
= += = *= /= assignment operator RL
/= %= &= ^=
|= <<= >>=
, comma operator LR

The precedence rule says that the addition operator has higher precedence than logical AND and
assignment operator. Therefore, first the addition of x and 10 is done, then the subtraction of 5 from z
is done. Now, both the operands of the logical AND are evaluated and depending on the values of x
and z, the value (either 1 or 0) is assigned to variable y.
We can change the priority of an operator by enclosing it in parentheses. For example
x = 10; y = 5; z = x * y  5; z = x * (y  5);

In the third statement, first of all x and y will be multiplied and then 5 will be subtracted from that
value giving the result as 45 while in the fourth statement first 5 is subtracted from y and then the
result is multiplied by x giving the result as 0. Thus, the use of parentheses can alter the precedence of
operators.
11.9.5 Type-Conversion and Cast Operators
C permits mixing of constants and variables of different types in an expression. C automatically
converts any intermediate values to the appropriate type.
Mixed mode Conversion
Consider the following statement :
x = 10 * 4.3;
The arithmetic expression contains one operand of type int and another of type float. In C, this is
not considered as an error, instead the integer value is automatically converted to type double for the
calculation. This is known as implicit conversion.
The lower type is automatically converted to the higher type before the operation proceeds. The
final result of an expression is converted to the type of the variable on the left of the assignment sign
before assigning the value to it. However, the following changes are introduced during the final
assignment.
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits.
3. long int to int causes dropping of the excess higher order bits.
Operators and Expressions 41

The conversion of lower types to the higher types can be shown as a waterfall model as depicted Remarks
in fig. 11.1.

signed char short signed int

unsigned char short unsigned int

int

unsigned int

long int

long unsigned int

float

double

long
double

Fig. 11.1 Waterfall model for implicit type conversion

Cast Operator
The C programmer has also the choice of explicitly specifying how the values are to be converted
in a mixed-mode expression. This feature is known in C as coercion and is accomplished by using the
cast operator. The cast operator is a unary operator and is used to convert a type to a different type
explicitly.
The word ‘cast’ is actually never used, instead the name of the data type to which the conversion
is to be made (such as int or float) is enclosed in parentheses and placed directly to the left of the
value to be converted. For example, consider the statement
int a = 9;
float b;
b = (float) a + 10.0;
The cast operator converts the value of a to its equivalent float representation before the addition
of 10.0 is carried out. The general form of cast is
(type-name) expression;
where type-name is one of the standard C data types. The expression may be a constant, variable or an
expression.
42 Programming in C and Numerical Analysis

Remarks 11.10 MATHEMATICAL FUNCTIONS


In many situations the mathematical functions such as sqrt( ), pow( ), log( ) etc. are needed.
Almost every C compiler supports these basic mathematical functions. All these functions are
available in a header file math.h so we must include this file in the beginning of the program as :
#include<math.h>
Argument to every function must be properly supplied. For example, sqrt( ) and log( ) functions
cannot take a negative number as the argument.
The following table gives a list of some mathematical functions which are used frequently :
Function Type of function What it does ?
abs(i) int Returns the absolute value of i
acos(d) double Returns the arc cosine of d
ceil(d) double Returns a value rounded upto the next higher
integer of d
cos(d) double Returns the cosine of d
cosh(d) double Returns the hyperbolic cosine of d
exp(d) double Raise e to the power d where e is the base of
natural logarithms (value 2.7182818)
fabs(d) double Returns the absolute value of double d
floor(d) double Returns the value rounded down to the largest
integer less than or equal to d
fmod(d1,d2) double Returns d1 modulo d2, the remainder of d1, d2
with sign of d1.
log(d) double Returns the natural logarithm of positive number d
log10(d) double Returns the logarithm to the base 10 of positive
number d
pow(d1, d2) double Returns the value of d1 raised to the power d2
pow10(i) double Returns the value of i raised to the power 10
sqrt(d) double Returns the square root of positive number d
In the table given above, the letter(s) enclosed in parentheses after the function name specify the
parameter (argument) list as described below :
d  specifies a doubleprecision type parameter
i  specifies an integer parameter
Type of function specifies the result obtained on using the function. In case of trigonometric
and hyperbolic functions d, d1 and d2 are in radians.
Program 1 :
/* Program to show the use of sqrt( ) function */
#include <math.h>
#include <stdio.h>
void main ( )
{
double a;
printf(“Enter the number whose square root is to be found : ”);
scanf(“%lf”, &a);
printf(“The square root of %lf is %lf”, a, sqrt(a));
}
Output
Enter the number whose square root is to be found : 9
The square root of 9.000000 is 3.000000
Operators and Expressions 43

Program 2 : Remarks
/* Program to find sum of two numbers */
#include <stdio.h>
void main( )
{
int x, y;
int z;
printf(“\nEnter value of x and y : ”);
scanf(“%d %d”, &x, &y);
z = x + y;
printf(“The value of z = x + y is %d”, z);
}
Output
Enter value of x and y : 4 5
The value of z = x + y is 9

Program 3 :
/* Program to find circumference of a circle */
#include <stdio.h>
void main( )
{
int r, circumference;
printf(“\nEnter value of radius: ”);
scanf(“%d”, &r);
circumference = 3.14*2*r;
printf(“The circumference of circle is %d”, circumference);
}
Output
Enter value of radius : 1
The circumference of circle is 6.280000.
Program 4 :
/* Program to find the area of a triangle */
#include <stdio.h>
#include <math.h>
void main ( )
{
float x, y, z, s, area;
printf(“Enter three sides of triangle\n”);
scanf(“%f %f %f, &x, &y, &z);
s = (x + y + z)/2;
area = sqrt(s*(sx)*(sy)*(sz);
printf(“Area of triangle is %f”, area);
}
Program 5 :
/*Program to interchange the values of two variables */
#include <stdio.h>
#include <math.h>
void main( )
{
float x, y, temp;
44 Programming in C and Numerical Analysis

printf(“Enter two numbers\n”);


Remarks scanf(“%f %f”, &x, &y);
temp = x;
x = y;
y = temp;
printf(“Values of numbers after interchange are %f %f”, x, y);
Program 6 :
/* Program to calculate compound interest */
#include <stdio.h>
#include <math.h>
void main ( )
{
float principal, rate, time, n, amount, CI;
printf(“Enter the principal : Rs”);
scanf(“%f”, &principal);
printf(“Enter the rate :”);
scanf(“%f”, &rate);
printf(“Enter the time period :”);
scanf(“%f”, &time);
printf(“The compound interest is”);
n = 1 + (rate/100);
amount = principal*pow(n, time);
CI = amount  principal;
printf(“%f”, CI);
}
Output
Enter the principal : Rs 100
Enter the rate: 12
Enter the time period : 4
The compound interest is 57.351944

Exercise 3.1
1. What is meant by operator precedence?
2. What is meant by Associativity?
3. How many relational operators are there and what are they? What is the difference between two
operators = and ==? What symbols are used for the logical operators AND and OR?
4. Describe the six assignment operators. What is the purpose of each operator?
5. What do you mean by type conversion? Why it is necessary? Explain different type of
conversions in C language.
Keyword
Arithmetic operator, relational operator, logical operator, assignment operator,
increment/decrement operator, priority and Associativity.
Summary
In this chapter we have studied various types of operators with their use in care of
Associativity and priority so that they give correct mathematical meaning and so that results comes as
per mathematical rules and lastly we studied library function math.h.
Remarks
CHAPTER – IV
DECISION CONTROL AND LOOPING
4.0 STRUCTURE
4.1 Introduction
4.2 Objective
4.3 Structured Language
4.4 Control Structures
4.5 The If Statement
4.6 Nested If….else Statements
4.7 The else-if Ladder
4.8 The Switch Statement
4.9 Loop
4.10 Loop Control Statement
4.1 INTRODUCTION
Many programs need to execute some particular statements if and only if a particular condition is
true. This is called conditional execution of the program. Similarly, in many cases we need to select
only one group of statements from several group of instructions or we need to perform selection.
Many programs need a group of instructions to be repeated either until and unless some condition
is satisfied or for a predetermined number of times. It is known as looping or iteration. These are all
cases of making decisions. The decision-making constructs in the C language are easy to use, but they
enable the computer to make some very sophisticated decisions.

4.2 OBJECTIVE
At the end of this chapter students should be able to
 Use of various type of loops (while, for, do-while)
 Use of various type of control structures (if-else, if, switch)

4.3 STRUCTURED LANGUAGE


The languages where programs consist of blocks of statements and the program flow is
determined by sequence, selection or iteration of statements, are known as structured languages such
as C, Fortran, Pascal. Control structures in a programming language provide the basic frame work,
within which operations and data are combined into programs and set of programs. It involves the
aspect of controlling the order of the execution of the operations known as sequence control. Most
programming languages provide a set of control statements or constructs to express different forms of
sequence like looping, conditional execution or selection. Before starting with the control statements
in C, let us first take a general overview of control structures.

4.4 CONTROL STRUCTURES


The control structures are of three types :
(i) Sequence
(ii) Selection(Branching)
(iii) Iteration (looping)
46 Programming in C and Numerical Analysis

Remarks 4.4.1 Sequence :


Sequence is the simplest control construct in a program. The program is in divided into a set of
instructions where each instruction has a specified task. The control passes sequentially from one
instruction to another instruction. At the start, the first instruction is executed, then the second and
then the subsequent ones resulting in a linear straight line flow of control.

Entry

Instruction 1

Instruction 2

Instruction 3

Instruction 4

Instruction 5

Instruction n

Stop
Decision Control and Looping 47

4.4.2 Selection :
Remarks
In selection, a particular group of statements is selected from several groups of instruction,
depending upon the out come of the selection condition or branching condition. These groups of
statements are called Branches. At a time only one of the branches is selected and the control then
passes to that branch. Instructions in that branch are then executed sequentially. This is called
condition execution or branching of the program.

Entry

Condition

Branch 1 Branch 2
Instruction Instruction

Instruction Instruction

Instruction Instruction

Sequence of
instruction

Stop

4.4.3 Looping :
Repetition of a group of instructions is called looping. Sometimes, it is required that we repeat a
group of instructions again and again depending upon the outcome of an looping condition. If the
outcome of the condition is true then the control shifts back to the first instruction of the group and all
the instructions are repeated again.
48 Programming in C and Numerical Analysis

Remarks Entry

Instruction

Instruction

Instruction

Instruction

Looping
condition

Stop

4.5 THE IF STATEMENT


C allows decisions to be made by evaluating a given expression as true or false. Such an
expression involves the use of relational and logical operators. Depending on the outcome of the
decision, the program executes in one of the two directions.
The C construct that allows this test to be performed is called the “if-else” statement. The “else”
portion of the if-else statement is optional. In its simplest form, the if statement is :
if (expression)
{
Statement-block;
}
The keyword ‘if’ must be followed by an expression to be tested, enclosed in parentheses. The
statements following the if statement will be executed only if the expression evaluates as true,
otherwise, the program control resumes after the closing brace “}”. This ends the if statement. The
first statement after the “if” expression is included automatically in the “if” statement. For two or
more statements it is necessary to surround them in braces otherwise only the first statement will be
executed. Consider the following fragments :
Decision Control and Looping 49

Entry Remarks

Test expression True

Statement block

Rest of Program

Flow-chart of simple if control

if (x > 0)
printf(“x is positive integer”);
printf(“\n value of x is %d”, x);
In this example if the value of x is greater than zero, then both the printf statements will be
executed otherwise only the second printf statement will be executed.
According to if-else statement, either statement1 or statement2 must be executed. After this,
program flow control goes to the statement immediately after the if-else statement. The logical
expression or test-condition may be designed with arithmetic, Boolean, character or user defined data
items. It can be shown with the help of flowchart given below :

Is logical expression ?

Statement 2 Statement 1

Next statement (if any)


50 Programming in C and Numerical Analysis

Remarks For example,


if(x > y)
printf(“%d”, x);
else
printf(“%d”, y);
So, the main difference between if and if-else is that the statement in case of former may or may
not execute but in case of later one statement out of two must be executed.
Program 1 :
/* Program to check equality of two numbers */
#include <stdio.h>
void main( )
{
int x, y;
printf(“Enter the values of x and y :”);
scanf(“%d %d”, &x, &y);
if (x = = y)
{
printf(“x is equal to y”);
}
else
{
printf(“x is not equal to y”);
} }
Output
Enter the values of x and y : 0 3
x is not equal to y
Program 2 :
/* Program for testing a leap year */
#include <stdio.h>
void main ( )
{
int year;
printf(“Please enter an year :”);
scanf(“%d”, &year);
/*single statement after ‘if’ and ‘else’, ‘{’ and ‘}’ not used */
if (year % 4 = = 0 && year % 100 != 0 | | year % 400 = = 0)
printf(“%d is a leap year”, year”);
else
printf(“%d is not a leap year”, year);
}
Output 1
Please enter an year : 1600
1600 is a leap year
Output 2
Please enter an year : 1905
1905 is not a leap year
Decision Control and Looping 51

4.6 NESTED IF….ELSE STATEMENTS Remarks


A clause of the if statement may itself contain another if statement. This is known as nested of ‘if’
statements (i.e., embedding of it within another if).

Entry

False
True
Test expression1

Statement block Statement block

True False
Test expression2

Statement block Statement block

Rest of Program

Flowchart of nested if….else statement


Program 3 :
/* Program to find greatest of three numbers */
#include <stdio.h>
void main ( )
52 Programming in C and Numerical Analysis

{
int x, y, z;
printf(“Enter the values of x, y, z :”);
scanf(“%d %d %d”, &x, &y, &z);
Remarks if(x > y)
{ if(x > z)
printf(“x is greatest”);
else
printf(“z is greatest”);
}
else
{ if(y > z)
printf(“y is greatest”);
else
printf(“z is greatest”);
}
}
Output :
Enter the values of x, y, z : 5 7 10
z is greatest
 A logical AND(&&) operation is equivalent to nesting an if within an if statement.
 A logical OR ( | | ) operation is equivalent to nesting an if within the else statement.

Program 4 :
/* Program to find greatest of three numbers */
#include <stdio.h>
void main ( )
{
int x, y, z;
printf(“Enter the values of x, y, z :”);
scanf(“ %d %d %d”, &x, &y, &z);
if((x > y) && (x > z))
printf(“x is greatest”);
else
{
If((y > x) && (y > z))
printf(“y is greatest”);
else
printf(“z is greatest”);
}
}
Output :
Enter the values of x, y, z : 5 7 10
z is greatest
4.7 THE ELSE-IF LADDER
Another form of nesting multiple if’s together is by using the else if ladder. It is a chain if’s in
which the statement with each else is an if. It takes the following form :
if (condition 1)
{ statement block 1 }
Decision Control and Looping 53

else if (condition 2)
{ statement block 2 }
else if (condition 3)
{ statement block 3 }
else if (condition n) Remarks
{ statement block n }
else
{ statement block n + 1 }
Entry

True False
Condition1

Statement block 1 True False


Condition2

Statement block 2 True False


Condition3

Statement block 3 True False


Condition n

Statement block n Statement block n+1

Rest of Program

Flowchart of else if ladder

Program :
Write a program to calculate gross salary of an employee.

Basic Pay (bp) HRA D.A.


bp  20000 10% of bp 30% of bp
20000 < bp  30000 15% of bp 35% of bp
30000 < bp  40000 20% of bp 40% of bp
>40000 25% of bp 45% of bp

/* Program to calculate gross salary of an employee */


#include <stdio.h>
#include <conio.h>
54 Programming in C and Numerical Analysis

void main ( )
{
float bp, hra, da, gs;
clrscr( );
printf(“Enter basic pay of an employee”);
Remarks scanf(“%f”, &bp);
if (bp < = 20000)
{
hra = (bp*10)/100;
da = (bp*30)/100;
}
else
{
if(bp < = 30000)
{
hra = (bp*15)/100;
da = (bp*35)/100;
}
else
{
if(bp < = 40000)
{
hra = (bp*20)/100;
da = (bp*40)/100;
}
else
{
hra = (bp*25)/100;
da = (bp*45)/100;
}
}
}
gs = bp + hra + da ;
printf(“Gross salary is %f”, gs);
}

4.8 THE SWITCH STATEMENT


In else-if statement, the complexity of a program increases dramatically if number of alternatives
increase. The program become complex means difficult to read and follow. It also confused the
programmer who design it. To remove this complexity problem C has a built-in multi way statement
which is known as ‘switch’. Switch statement allows a selection out of several available groups.
The general from the switch statement is :
switch(expression)
{ case exp1 :
statement block-1
break;
case exp2 :
statement block-2
break;
Decision Control and Looping 55

………………….
………………….
default :
default block
}
The exp represent constant, integer valued expression. They are usually written either as an Remarks
integer constant or as a character constant and are known as case labels. Each of these values should
be unique within a switch statement.
When the switch is executed, the expression is evaluated and control is transferred directly to the
group of statements whose case-label matches the value of the expression. The break statement at the
end of each block signals the end of that particular case and causes control to be transferred out of the
switch statement, thus preventing the remaining groups from being executed.
The default is an optional case. This group will be selected if none of the case labels matches the
value of the expression. It generally used far the case of error.
Note :
(1) The default may be appear any where within switch.
(2) Switch can be nested within switch.
(3) If none of the case labels match the value and default is not present, then no action is taken.
(4) To improve readability of code, we use default at end.
(5) 257 case labels are possible in switch.
(6) Nesting of switch statement upto 15 levels.
Entry

Switch
expression

False False False False


exp1 exp2 exp3 exp n

True True True True

Block 1 Block 2 Block 3 Block n default block

Rest of program

Example :
switch(ch)
{
Flowchart of switch statement
case 3 :
c=a+b;
printf(“The value of c is %d”, c);
break;
case 4 :
56 Programming in C and Numerical Analysis

c=a*b;
printf(“The value of c is %d”, c);
break;
default :
printf(“Neither sum nor product”);
}
Remarks If we take a = 1 b = 5
If assume ch = 3 output is – The value of c is 6
ch = 4 output is – The value of is 5
ch = 1 output is – neither sum nor product.
4.9 LOOP
There may be a situation, when you need to execute a block of code several number of times. In
general, statements are executed sequentially. The first statement in a function is executed first,
followed by the second, and so on. Programming languages provide various control structures that
allow for more complicated execution paths. A loop statement allows us to execute a statement or
group of statements multiple times and following is the general form of a loop statement in most of
the programming languages :
4.9.1 Types of Loops
Depending on the position of the control statement in the loop, a control structure may be
classified either as the entry controlled loop or as the exit controlled loop. In the entry controlled loop,
the control conditions are tested before the start of the loop execution. The body of loop will be
executed only when loop conditions are satisfied. While in the case of an exit controlled loop, the test
condition is evaluated at the end of the loop and depending on the outcome, the body of loop is
executed again. In exit controlled loop, the body of loop is executed unconditionally for the first time.
The entry controlled and exit controlled loops are also known as pre-test and post-test loops
respectively.
The test conditions should be carefully stated in order to execute the loop for a desired number of
times. In loops, it is assumed that the test condition will eventually transfer the control out of the loop.
In case, due to some reason it does not do so, the control enters into an infinite loop and the body is
executed unendingly over and over again. Generally, a looping process would include the following
steps : Entry Entry

test Body of
False the loop
condition

True
test True
Body of
condition
the loop

False

Exit

Exit

Entry control Exit control


Decision Control and Looping 57

1. Setting and initialization of a condition variable.


2. Execution of the statement in the loop.
3. Test for a specified value of the condition variable for the execution of the loop. Remarks
4. Incrementing, decrementing or updating the condition variable.
The test may be either to determine whether the loop has been repeated the specified number of
times or to determine whether the particular condition has been met or not.
Based on the nature of the condition variable and the value assigned for testing the control
expression, the loop may be classified into two general categories :
1. Counter controlled loops
2. Sentinel controlled loops
In counter-controlled loops, we know in advance exactly how many times the body of loop will
be executed. The control head specifies a variable known as counter to control the number of
executions. The counter must have an initial value, final value and increment (or decrement) so that
counter is properly tested and updated for the desired loop operations. The number of times we want
to execute the loop may be a constant or a variable with an assigned value. A counter-controlled loop
is also called as definite-repetition loop.
In the case of sentinel-controlled loops, a special value or sentinel value is used to change the
loop control expression from true to false. The control variable is known as sentinel variable. A
sentinel-controlled loop is also called indefinite-repetition loop since the number of repetitions or
execution is not known before the loop begins executing.
The C language provides three constructs for performing the various loop operations, viz :
1. The while statement
2. The do-while statement
3. The for statement
1. The While Statement
A while statement in C programming language repeatedly executes a target statement as long as a
given condition is true.
Syntax :
The syntax of while loop in C programming language is :
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.
Flow Diagram :

Condition

If condition
If condition is false
is true
Code block
58 Programming in C and Numerical Analysis

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Remarks Example :
#include <stdio.h>
void main ( )
{
/* local variable definition */
int a = 10;
/* While loop execution */
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
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

2. The For Statement


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 :
The syntax of a for loop in C programming language is:
for (initialization; condition; increment)
{
Statement(s);
}

Here is the flow of control in a for loop:


1. The initialization(Init) step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
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 doe4s not execute and flow of control jumps to the next statement just after the
for loop.
Decision Control and Looping 59

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. This statement can be
left blank, as long as a semicolon appears after the condition.
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.
Flow Diagram : Remarks

Init

condition

If condition
is true
Code block
If condition
is false

Increment

Example :
#include <stdio.h>
void main ( )
{
/* for loop execution */
for (int a = 10; a < 20; a = a + 1)
{
Printf(“value of a : %d\n”, a);
}
}
When the above code is compiled and executed, it process 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
60 Programming in C and Numerical Analysis

value of a : 17
value of a : 18
value of a : 19

3. THE DO-WHILE STATEMENT


Unlike for and while loops, which test the loop condition at the top of the loop, the do…while loop in
C programming language checks its condition at the bottom of the loop.
Remarks 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 :
The syntax of a do…while loop in C programming language is :
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.
Flow Diagram :

Code block

If condition
is true
condition

If condition
is false

Example :
#include <stdio.h>
void main ( )
{
/* local variable definition */
int a = 10;
Decision Control and Looping 61

/* do loop execution */
do
{
printf(“value of a : %d\n”, a);
a = a + 1;
}while (a < 20);
}
When the above code is compiled and executed, it produces the following result : Remarks
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
4.10 LOOP CONTROL STATEMENT
Loop control statement change execution from its normal sequence. When execution leave4s a scope,
all automatic objects that were created in that scope are destroyed.
Break Statement
The break statement in C programming language has the following two usages :
1. When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the
execution of the innermost loop and start executing the next line of code after the block.
Syntax :
The syntax for a break statement in C is as follows :
break ;

Flow Diagram :

Conditional code

If condition
Example : is true
#include <stdio.h> condition break
void main ( )
{
/* local variable definition */
int a = 10; If condition
/* while loop execution */ is false
while ( a < 20)
{
printf(“value of a : %d\n”, a);
62 Programming in C and Numerical Analysis

a++;
if (a > 15)
{
/* terminate the loop using break statement */
break;
}
}
}
When the above code is compiled and executed, it produces the following result :
Remarks
value of a : 10
value of a : 11
value of a : 12
value of a : 13
value of a : 14
value of a : 15

Continue Statement
The continue statement in C programming language works somewhat like the break statement.
Instead of forcing termination, however, continue forces the next iteration of the loop to take place,
skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do…while loops, continue statement causes the program control passes to
the conditional tests.
Syntax :
The syntax for a continue statement in C is as follows :
continue;
Flow Diagram :

Conditional code

If condition continue
is true
condition

If condition
Example : is false
#include <stdio.h>
void main ( )
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
Decision Control and Looping 63

{
if (a = = 15)
/* skip the iteration */
continue;
}
printf(“value of a : %d\n”, a);
a++;
}while (a < 20);
}
When the above code is compiled and executed, it produces the following result : Remarks
value of a : 10
value of a : 11
value of a : 12
value of a : 13
value of a : 14
value of a : 16
value of a : 17
value of a : 18
value of a : 19
Goto statement
A goto statement in C programming language provides an unconditional jump from the goto to a
labeled statement in the same function.
Note : Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. Any program that uses a goto can be rewritten so that it doesn’t need the goto.
Syntax :
The syntax for a goto statement in C is as follows :
goto label;

..
label : statement ;
Here label can be any plain text except C keyword and it can be set any where in the C program
above or below to goto statement.
Flow Diagram :

lable 1 Statement 1

Statement 1 goto
lable 2 lable 3

lable 3 Statement 1
64 Programming in C and Numerical Analysis

Example :
#include <stdio.h>
void main ( )
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP : do
{
if (a = = 15)
/* skip the iteration */
Remarks a = a + 1;
goto LOOP;
}
printf(“value of a : %d\n”, a);
a++;
}while (a < 20);
}

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 : 16
value of a : 17
value of a : 18
value of a : 19

Exercise 4.1
1. Differentiate between switch and else-if ladder.
2. Describe the purpose and syntax of various decision-making constructs in C language.
3. What is the purpose of while, for and do-while loops? How these loops are executed?
4. Differentiate between the following :
(i) for and do-while loop
(ii) break and continue
(iii) while and do-while loop
(iv) break and switch statements
(v) while and for
(vi) continue and goto

Keywords
If-else, while, for, do-while, switch, continue, goto and break.
Summary
Decision Control and Looping 65

In this unit we have studied various types of loops, decision control structures with suitable
programming examples. They include continue, goto and break statements.
Remarks

CHAPTER – V
FUNCTION AND C – PREPROCESSOR
5.0 Structure
5.1 Introduction
5.2 Objective
5.3 C – Functions
5.4 Function Call By Value in C
5.5 C-Recursion
5.6 The C- Preprocessor
5.7 File inclusion Directive
5.8 Macro
5.9 Predefined Macros
5.10 Conditional Compilation Directives
5.1 INTRODUCTION
Many strength of C language is C functions because they are easy to define and use. C
functions can be classified into two categories namely, library functions and user defined functions.
main( ) is example of user defined functions. printf ( ) and scanf( ) belongs to the category of library
function.
The C preprocessor provides several tools that are unavailable in other high-level languages. The
programmer can use these tools to make his program easy to read, easy to modify.
5.2 OBJECTIVE
At the end of this chapter students should be able to
 How a function is designed?
 How a function is integrated into a program?
 How two or more functions are put together?
 Use of various types of preprocessor directive with examples.
5.3 C – FUNCTIONS
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main( ), and all the most trivial programs can define additional functions.
You can divide up you code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function performs a
specific task.
A function declaration tells the compiler about a function’s name, return type, and parameters. A
function definition provides the actual body of the function.
The C standard library provide4s numerous built-in functions that your program can call. For
example, function strcat( ) to concatenate two strings, function memcpy( ) to copy one memory
location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure, etc.
Defining a Function :
The general form of a function definition in C programming language is as follows :
return_type function_name (parameter list)
{
Body of the function
}
A function definition in C programming language consists of a function header and a function body.
Here are all the parts of a function :
Function and C-Preprocessor 67

Remarks 1. Return type : A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
2. Function Name : This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
3. Parameters : A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list refers
to the type, order and number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
4. Function Body : The function body contains a collection of statements that define what the
function does.
Example :
/*function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Function Declaration :
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
A function declaration has the following parts :
return_type function_name (parameter list);
For the above defined function max( ), following is the function declaration :
int max (int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration :
int max( int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case you should declare the function at the top of the file calling the
function.

Calling a Function :
When creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function perform the defined task.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its function-ending
closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and
if function returns a value, then you can store returned value. For example :

#include <stdio.h> Remarks


/* function declaration */
68 Programming in C and Numerical Analysis

int max(int num1, int num2);


int main ( )
{
/*local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf(“Max value is : %d\n”, ret);
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max( ) function along with main( ) function and compiled the source code. While running
final executable, it would produce the following result :
Max value is : 200
Function Arguments :
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
5.4 FUNCTION CALL BY VALUE IN C
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the parameter inside
the function have no effect on the argument.
By default, C programming language uses call by value method to pass arguments. In general,
this means that code within a function cannot alter the arguments used to call the function. Consider
the function swap( ) definition as follows :
/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Function and C-Preprocessor 69

Remarks Now, let us call the function swap( ) by passing actual values as in the following example :
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main ( )
{
/* local variable definition */
int a = 100;
int b = 200;
printf(“Before swap, value of a : %d\n”, a);
printf(“Before swap, value of b : %d\n”, b);
/*calling a function to swap the values */
swap(a, b);
printf(“After swap, value of a : %d\n”, a);
printf(“After swap, value of b : %d\n”, b);
return 0;
}

Let us put above code in a single C file, compile and execute it, it will produce the following result :
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200
Which shows that there is no change in the values though they had been changed inside the function.
5.5 C-RECURSION
Recursion is the process of repeating items in a self-similar way. Same applies in programming
languages as well where if a programming allows you to call a function inside the same function that
is called recursive call of the function as follows :
void recursion ( )
{
recursion ( ); /* function calls itself */
}
int main ( )
{
Recursion ( );
}
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function, otherwise it
will go in infinite loop.
Recursive function are very useful to solve many mathematical problems like to calculate
factorial of a number, generating Fibonacci series, etc.

Number Factorial :
Following is an example, which calculates factorial for a given number using a recursive function :
#include <stdio.h>
int factorial (unsigned int i)
{
if (i <= 1)
{ Remarks
70 Programming in C and Numerical Analysis

return 1;
}
return i * factorial(i  1);
}
int main ( )
{
int i = 15;
printf(“Factorial of %d is %d\n”, i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result :
Factorial of 15 is 2004310016
Fibonacci Series :
Following is another example, which generates Fibonacci series for a given number using a
recursive function :
#include <stdio.h>
int fibonaci(int i)
{
if(i = = 0)
{
return 0;
}
if (i = = 1)
{
return 1;
}
return fibonaci(i  1) + fibonaci(i  2);
}
int main ( )
{
int i;
for(i = 0; i < 10; i++)
{
printf(“%d\t%n”, fibonaci(i));
}
return 0;
}
When the above code is compiled and executed, it produces the following result :
0 1 1 2 3 5 8 13 21 34
5.6 THE C- PREPROCESSOR
Constants features is not included in the original C language. To include this feature authors
developed the C-preprocessor. The C-preprocessor is not part of the compiler, but is a separate step in
compilation process, this is first a text substitution tool and they instruct compiler to do required pre-
processing before starting actual compilation.
The preprocessor directives follows special syntax rules that are different from the normal C
syntax
1. All preprocessor commands begin with # symbol.
2. There can be no space between the number sign and directive.
Function and C-Preprocessor 71

3. The directive is not terminated by a semicolon.


Remarks 4. Only one directive can appear on a line.
These directive can be divided in to four categories
1. File inclusion directives
2. Macro substitution directives
3. Compiler control directives
4. Other directives

5.7 FILE INCLUSION DIRECTIVE


A external file contains useful constants, function declarations and macro definitions which was
used in almost all program.
#include<file_name>
where file name is the name of the file containing the required definitions or function. Usually these
files are include in beginning of a program but they can be included at any point. Such files are called
header files and have extension .h.
e.g. #include<stdio.h>
#include<math.h>
#define directive
The #define directive is used to define a symbol to the preprocessor and assign it a value. The
symbol is meaningful to the preprocessor only in the program code following the definition. For
example,
#define SIZE 5
#define TRUE 1
#define AND &&
#undef directive
The #undef directive is used to redefine a macro at some point in a program (if necessary). If a
preprocessor symbol has already been defined, it must be undefined before being redefined. This is
accomplished by the use of #undef directive, which specify the name of the symbol to be undefined.
For example,
The macro template SIZE define above can be redefined with value \0 as shown below :
#undef SIZE /* undefined SIZE */
#define SIZE /* redefine SIZE */
#undef SIZE /* undefined SIZE again */
It is not necessary to perform redefinition at the beginning of the program. A symbol need not be
redefined after it has been undefined. However, if the symbol is used after it has been undefined, it
will not be replaced. Further, a defined symbol will be replaced only till the point at which it is
undefined.
5.8 MACRO
When a preprocessor symbol is defined as a segment of text or string it is more generally called a
macro. Macros are very useful in making C code more readable and compact. For example,
#define cube(N)(n*N*N)
main ( )
{
int x = 3, y = 2, z;
z = cube(x + y);
printf(“%d”,z);
}
72 Programming in C and Numerical Analysis

The above program has a macro named cube, which find the cube of a number. The output of Remarks
above program will be as the macro expansion will be
z = ((x+y)*(x+y)*(x+y));
The following points should be taken into consideration while defining macros :
(i) Use capital letters for macro template so that it can be easily recognized when reading through the
program. It is not compulsory, i.e., we can use small letters also.
(ii) A macro template and its macro expansion are separated by blanks or tabs.
(iii) Never terminate a macro definition by a semicolon.
(iv) Don’t leave a blank between the macro template and its arguments when the macro is defined.
(v) Always enclose the macro expansion within parentheses to avoid any confusion to the user and
unexpected results (i.e., side effects).
(vi) Type of a macro is never declared.

Example : Define a macro VOLUME having argument r for find the volume of a sphere. Write a C
program to use it in main ( ) function.

Solution :
/* compute the volume of a sphere using a macro having argument r */
#include<stdio.h>
#define PI 3.14159
#define VOLUME(r) (4.0/3.0*PI*r*r*r)
main ( )
{
float radius, vol;
clrscr ( );
printf(“\n Enter the radius of sphere\n\n”);
scanf(“%f”, &radius);
if(radius < 0.0)
printf(“\nVolume of sphere is not possible \n\n”);
else
{
vol = VOLUME(radius);
printf(“\nVolume of sphere is %2f cubic units\n\n”,vol);
}
getch( );
}
Function and C-Preprocessor 73

Remarks 5.9 PREDEFINED MACROS


ANSI C defines a number of macros. Although each one is available for you use in programming, the
predefined macros should not be directly modified.

Description

Macro
_DATE_ The current date as a character literal in “MMM DD YYYY” format.
_TIME_ The current time as a character literal in “HH:MM:SS” format.
_FILE_ This contains the current file name as a string literal.
_LINE_ This contains the current line number as a decimal constant.
_STDC_ Defined as 1 when the compiler complies with the ANSI standard.

Let’s try the following example :

#include <stdio.h>
main ( )
{
printf(“File : %s\n”,_FILE_);
printf(“Date : %s\n”, _DATE_);
printf(“Time : %s\n”, _TIME_);
printf(“Line : %d\n”, _LINE_);
printf(“ANSI %d\n”,_STDC_);

When the above code in a file test.c is compiled and executed, it produces the following result :
File : test.c
Date : Jun 5 2012
Time : 01:36:24
Line : 9
ANSI : 1

5.10 CONDITIONAL COMPILATION DIRECTIVES


Sometimes it is necessary to have two versions of a program. The preprocessor provides us
various directives which help in conditional processing of the programs. These directives are
1. #ifdef
2. #ifndef
3. #endif
4. #if
5. #else
6. #elif

The #if Direcitve


The #if directive tests an expression. The expression can be of any form used in a C program,
with virtually any operators, except that it can include only integer constant values. In this directive
neither variables or function calls nor floating point, character or string constants are permitted. The
#if directive is true if the expression evaluates to true.
74 Programming in C and Numerical Analysis

The #ifdef Directive Remarks


The #ifdef directive tests whether a particular symbol has been defined or not. It does not matter
what value has been assigned to the symbol. In fact, a symbol can be defined to the preprocessor
without a value.

The #ifndef Directive


The preprocessor also provide the directive #ifndef which results in true if a symbol is not
defined. This makes it possible to switch between two versions using a single switch.

The #else, #elif, #endif Directive


These directives function in the same way as the else clause, else-if clause or endif clause of an if
statement.

Applications
All these conditional directives work by testing whether a symbol has been defined by a #define
directive or not. There are various types of constructs available for conditional compilation like

(1) #if<expression>
Statement block;
#else
Statement block;
#endif

If the expression following the #if directive evaluates to true (or non zero) then the compiler
compiles the lines following the #if directive, otherwise the compiler skips the lines that follow #if
until it encounters either a matching #else or #endif directive. If there is a matching #else and #endif
are compiled.
Any undefined preprocessor symbol used in the #if expression is treated as if it has the value 0.
Using a symbol that is defined with no value does not work with all preprocessors and an attempt to
do so might result in an error. The same rule applies to the symbols which are non-numeric or have
non-integer values unless these symbols can be evaluated as constant integers. For example, if three
macros are defined as :

#define A 4
#define B 5
#define SUM A + B
then SUM can be used in an #if expression, since it becomes 4 + 5 = 9. However, a symbol defined as
follows connot be used in an #if directive

#define Text @#!?


(2) #if<expression1>
statement block;
#elif<expression2>
statement block;
#else
Function and C-Preprocessor 75

statement block;
#endif
Remarks Exercise – 5.1
1. What is a function in C. Why do we use functions? What are different categories of functions in
C. Give examples.
2. What is recursion? How recursion is implemented in C language? Illustrate through a suitable
example.
3. What special advantage does a function of types int have?
4. Distinguish between local and global variables.
5. What do you mean by formal and actual arguments? Explain the concept of function prototype.
6. How can a preprocessor directive be written?
7. Differentiate between macros and functions.

Keywords : function, return, recursion, internal variable, external variable, #define.


Summary
We summarize the concept of function, recursive function and C-preprocessor with various
examples and their defining types.
Remarks
CHAPTER- VI
ARRAY, STRING AND STRUCTURE
6.0 STRUCTURE
6.1 Introduction
6.2 Objective
6.3 Array
6.4 Declaring Arrays
6.5 Initializing Arrays
6.6 Accessing Array Elements
6.7 Multidimensional Arrays
6.8 Two-Dimensional Arrays
6.9 Passing Arrays to Functions
6.10 C Programming String
6.11 Structures and Unions
6.12 Structures and Arrays
6.13 Structures and Functions
6.14 Unions
6.1 INTRODUCTION
We know that the fundamental data types, namely char, int, float double. Although types are very
useful, but these variable can stare only one value at any given time, so their use is limited. In many
application, we have to handle a large volume of data in terms of reading, printing and processing for
this we need derived data types. C supports a derived data-types known as array and string is special
type of array.
But in so many times, we needs a group of data items that belong to the same type. However, we
can not use an array if we want to represent a collection of data items of different types using a single
name C supports a constructed data type known as structure.
6.2 OBJECTIVE
At the end of this unit students should be able to
1. Declaration of array, string and structure.
2. Initialization of array, string and structure.
3. Implementation of array, string and structure.
4. Comparison between array, string, structure and union.
6.3 ARRAY
C programming language provides a data structure called the array, which can store a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data, but it
is often more useful to think of an array as a collection of variables of the same type. Instead of
declaring individual variables, such as num0, num1, …and num20, you declare one array variable
such as numbers and use num[0], num[1], and …., num[20] to represent individual variables. A
specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.

First Element Last Element


 
Num[0] Num[1] Num[2] Num[3] ……..
Array, String and Structure 77

Remarks 6.4 DECLARING ARRAYS


To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
type arrayName [ arraySize ]
This is called a single-dimensional array. The arraySize must be an integer constant greater than
zero and type can be any valid C data type. For example, to declare a 20-element array called num of
type float, use this statement :
float num [20];
Now num is avariable array which is sufficient to hold upto 20 float numbers.

6.5 INITIALIZING ARRAYS


You can initialize array in C either one by one or using a single statement as follows :
float num[4] = {100.0, 2.0, 3.4, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write :
float num [ ] = {100.0, 2.0, 3.4, 50.0};
You will create exactly the same array as you did in the previous example. Following is an
example to assign a single element of the array :
num [3] = 50.0;
The above statement assigns element number 4 th in the array with a value of 50.0. All arrays have
0 as the index of their first element which is also called base index and last index of an array will be
total size of the array minus 1. Following is the pictorial representation of the same array we
discussed above :

0 1 2 3
Num 100.0 2.0 3.4 50.0

6.6 ACCESSING ARRAY ELEMENTS


An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example :
float sum = num[2];
The above statement will take 3rd element from the array and assign the value to sum variable.
Example 1 : To read and print values into array
#include<stdio.h>
void main ( )
{
int i, arr[50], num;
printf(“\nEnter no of elements :”);
scanf(“%d”, &num);
//Reading values into Array
printf(“\nEnter the values :”);
for(i = 0; i < num; i++)
{
scanf(%d”,&arr[i]);
}
//Printing of all elements of array
for(i = 0; i < num; i ++) Remarks
78 Programming in C and Numerical Analysis

{
printf(“\n arr[%d] = %d”, arr[i]);
}
}
Output :-
Enter no of elements : 4
Enter the values 10 5 6 1
arr[0] = 10
arr[1] = 5
arr[2] = 6
arr[3] = 1

6.7 MULTIDIMENSIONAL ARRAYS


C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration :
type name[size1] [size2]…[sizeN];
For example, the following declaration creates a two dimensional 5, 4 integer array :
int two[5] [4];
6.8 TWO-DIMENSIONAL ARRAYS
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of
size x, y you would write something as follows :
type arrayName [x] [y];
where type can be any valid C data type and arrayName will be a valid C identifier. A two-
dimensional array can be think as a table which will have x number of rows and y number of columns.
A 2-dimensional array arr which contains three rows and four columns can be shown as below :

Column 0 Column 1 Column 2 Column 3


Row 0 arr[0][0] arr[0][1] arr[0][2] arr[0][3]
Row 1 arr[1][0] arr[1][1] arr[1][2] arr[1][3]
Row 2 arr[2][0] arr[2][1] arr[2][2] arr[2][3]

Thus, every element in array arr is identified by an element name of the form arr[i][j], where arr is the
name of the array, and i and j are the subscripts that uniquely identify each element in arr.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is
an array with 3 rows and each row has 4 columns.
int arr[3][4] = {
{0, 1, 2, 3}, /* initializers for row indexed by 0 */
{4, 5, 6, 7}, /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example :
int arr [3] [4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
Array, String and Structure 79

Remarks Accessing Two-Dimensional Array Elements


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array. For example :
int val = arr[3][2];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above
diagram. Let us check below program where we have used nested loop to handle a two dimensional
array :

#include <stdio.h>
void main ( )
{
/* an array with 4 rows and 2 columns */
int arr[4][2] = { {0, 0}, {1, 2}, {2, 4}, {4, 8} };
int i, j;
/* output each array element’s value */
for ( i = 0; i < 4; i ++)
{
for ( j = 0; j < 2; j++)
{
printf(“a[%d][%d] = %d\n”, i, j, arr[i][j] );
}
}
}

When the above code is compiled and executed, it produces the following result :
arr[0] [0] : 0
arr[0] [1] : 0
arr[1] [0] : 1
arr[1] [1] : 2
arr[2] [0] : 2
arr[2] [1] : 4
arr[3] [0] : 4
arr[3] [1] : 8
As explained above, you can have arrays with any number of dimensions, although it is likely that
most of the arrays you create will be of one or two dimensions.
Program : Program to sort an entire array using bubble sort
#include <stdio.h>
void main ( )
{
int i , j, temp, x[10];
printf(“\nEnter values for array elements :\n”);
for(i = 0; i < 10; i++) /*input data */
scanf(“%d”, &x[i]);
printf(“\nThe original unsorted array is : \n”);
for(i = 0; i < 10; i++)
printf(“%d\t”, &x[i]); /*Display unsorted data*/
for( i = 0; i < 9; i++) /*Sort the array*/
for(j = 0; j < 9; j++) Remarks
if(x[j] > x[j+1]) /* Swapping values */
80 Programming in C and Numerical Analysis

{
temp = x[j+1];
x[j+1] = x[j];
x[j] = temp;
}
printf(“\nThe sorted array is : \n”);
for(i = 0; i < 10; i++) /* Display sorted data*/
printf(“%d\t”,x[i]);
}
Output :
Enter values for array elements :
10 8 9 12 13 12 1 2 3 4
The original unsorted array is :
10 8 9 12 13 12 1 2 3 4
The sorted array is :
4 3 2 1 8 9 10 12 12 13

6.9 PASSING ARRAYS TO FUNCTIONS


Arrays can be passed to functions just like other variables. To pass a one-dimensional array to a
function, the name of the array without any subscripts and the size of the array are listed as
arguments. For example, the call
largest (num, n)
will pass the whole array num to the called function. In the definition of this function, the function
header might look like
float largest (float num [ ], int size)
The declaration of the formal argument array is made as :
float num [ ];
The pair of brackets informs the compiler that the argument num represents an array of numbers.
It is not necessary to specify the size of the array.
In C, the name of the array represents the address of its first element. By passing the name of the
array, the address of the array is passed to the called function. The array in the called function now
refers to the same array stored in the memory. Therefore, any changes made to the elements of the
array in the called function will be reflected in the original array.
Normal variables are passed to functions using call by value. Thus, the changes that a function
makes to these variables is not reflected after the function call in the calling function. On the other
hand, arrays are passed to functions using call by address, since array names refer to their address in
memory. Thus, the changes made to the array elements by the function are reflected in the calling
function.
The following program illustrates this mechanism :
/* Program to find largest value in an array */
#include <stdio.h>
void main ( )
{
float largest(float a[], int n);
float height[10], longest, i;
printf(“\nEnter data for array :\n”);
for(i = 0; i < 10; i++)
scanf(“%f”,&height[i]);
longest=largest(height,10);
Array, String and Structure 81

Remarks printf(“Largest value is %f”,longest);


}
float largest(float a [ ], int n)/* Function definition */
{
int i;
float longest;
longest = a[0];
for(i = 1; i < n; i++)
if(longest < a[i])
{
longest = a[i];
}
return (longest);
}

Output :
Enter data for array :
23 534 7876 28 4 67 334 56 765 9
Largest value is 7876.000000
6.10 C PROGRAMMING STRING
In C programming, array of character are called strings. A string is terminated by null character \0.
For example :
“c string tutorial”
Here, “c string tutorial” is a string. When, compiler encounters strings, it appends null character at the
end of string.
C s t r i n g t u t o r i a l \0

6.10.1 Declaration of strings


Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.
char ch[5];
ch[0] ch[1] ch[2] ch[3] ch[4]

6.10.2 Initialization of strings


In C, string can be initialized in different number of ways.
char ch[ ] = “abcd”;
OR,
char ch[5] = “abcd”;
OR ,
char ch[ ] = {‘a’, ‘b’, ‘c’, ‘d’, ‘\0’};
OR;
char ch[5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘\0’};

ch[0] ch[1] ch[2] ch[3] ch[4]


a B c d \0
82 Programming in C and Numerical Analysis

Character strings are often used to build meaningful and readable programs. The common Remarks
operations on character strings include :
1. Reading and writing strings
2. Copying one string to another
3. Concatenating strings (i.e., placing one behind another to form a new string)
4. Comparing strings for equality
6.10.3 Reading Strings from user
Reading words from user (By using scanf)
char ch[20];
scanf(“%s”, ch);
String variable ch can only take a word. It is because when white space is encountered, the scanf( )
function terminates.
Example : Write a C program to illustrate how to read string from terminal.
#include <stdio.h>
void main ( )
{
char ch[20];
printf(“Enter name :”);
scanf(%s”,ch);
printf(“Your name is %s.”, ch);
}

Output :
Enter name : MDU Rohtak
Your name is MDU.
Here, program will ignore Rohtak because, scanf( ) function takes only string before the white space.
Reading a line of text (By using getchar and gets function)
Example : C program to read line of text manually.
#include <stdio.h>
void main ( )
{
char name [20], ch;
int i = 0;
printf(“Enter name:”);
while(ch!= ‘\n’) //terminates if user hit enter
{
ch = getchar();
name[i]=ch;
i++;
}
name[i]=‘\0’; //inserting null character at end.
printf(“Name: %s”, name);
}
This process to take string is tedious. There are predefined functions gets( ) and puts in C language to
read and display string respectively.
void main ( )
{
Array, String and Structure 83

char name [20];


printf(“Enter name:”);
Remarks gets(name); //Function to read string from user.
printf(Name:”);
puts(name); //Function to display string.
}
Both, the above program has same output below :
Output :
Enter name : DDE Rohtak
Name : DDE Rohtak
Writing Strings to the Screen
The string can be displayed on the terminal using the familiar printf function. For example
printf(“%s”,name);
can be used to displayed the contents of the array name. Like getchar function, we have an equivalent
function putchar( ) to display the value of a character variable. It takes the following form :
char ch = ‘R’;
putchar(ch);
It displays the character ‘R’ on the screen. We can use the function putchar( ) repeatedly using a
loop, to display successive characters stored in an array. For example,
char name[9] = “Computer”;
for(i = 0; i<9; i++)
{
putchar(name[i]);
}
putchar(‘\n’);
A more convenient way of printing string values is to use the function puts( ) declared in the
header file <stdio.h>. It uses a string as a parameter and is called as :
puts(string);
where string is a character array. The function displays characters from the string variable string and
then moves the cursor to the beginning of the next line on the screen. The following statements read
line entered by the user using gets( ) and displays it on the screen using put( ) :
char line[80];
gets (line);
puts (line);
6.10.4 Concatenation of Strings
We cannot join two strings by simple arithmetic addition. That is, the statements such as
string1 = string2 + string3;
string1 = string2 + “ram”;
are not valid. To achieve the desired result, we have to copy characters from string2 and then
characters from string3 into string1. The size of the array string1 should be large enough to hold the
total characters. The process of combining two strings is called concatenation. This can be done
explicitly by using loops. However, we have a useful library function strcat( ) which performs this
string operation elegantly.
Strcat( ) Function
The strcat( ) function joins two strings together. It takes the following form :
strcat(string1, string2);
84 Programming in C and Numerical Analysis

where string1 and string2 are character arrays. On its execution, string2 is appended to string1. The Remarks
null character at the end of string1 is removed and string2 is placed there, whereas the string in string2
remains unchanged. For example, consider the following three strings :
0 1 2 3 4 5 6 7 8 9 10 11 12
string1= A B C D E \0

0 1 2 3 4 5
string2= F G H I \0

0 1 2 3 4
String3= J K L \0

strcat(string1, string2);
Execution of this statement results in
0 1 2 3 4 5 6 7 8 9 10 11 12
string1= A B C D E F G H I \0

0 1 2 3 4 5
string2= F G H I \0

while the statement


strcat(string1, string3);

result in
0 1 2 3 4 5 6 7 8 9 10 11 12
string1= A B C D E J K L \0

0 1 2 3 4
String3= J K L \0

The size of string1 should be large enough to accommodate the resultant concatenated string.
The strcat function may also append a string constant to a string variable. For example, the
following is perfectly valid in C :
strcat(string1, “ram”);
C permits nesting of functions. For example, the statement
Strcat(strcat(string1, string2), string3);
is allowed and concatenates all the three strings together. The final string is stored in string1.
Program to illustrate use of strcat function
#include <stdio.h>
#include <string.h>
void main ( )
{
char string1[ ] = “ram”;
char string2[] = “Sham”;
char string3[] = “Rohtak”;
char string4[50];
string4 = strcat(string2(strcat(string1,string3)));
puts(string4);
string4 = strcat(string3(strcat(string2,string1)));
Array, String and Structure 85

puts(string4);
}
Remarks Output :
Sham ram Rohtak
Rohtak Sham ram
Strncat( ) Function
This is another concatenation function that takes three parameters and concatenates the n left most
characters of string2 to the end of string1. The general form of strncat( ) function is:
strncat(string1, string2, n);
For example, for the strings

str1= A B C D E \0

str2= F G H I \0

The execution of
strncat(str1, str2, 2)
results in :

str1= A B C D E F G \0

The strncat function appends one string to another followed by a null characters.
The following program illustrates the use of strncat function. Notice that the blank space in source
is also treated as a character.
Program to show the use of strncat function
#include <string.h>
#include <stdio.h>
void main ( )
{
char ch[25];
char [] = “Rohtak”
printf(“\nSource string is:%s”, s);
strcpy(ch, “DDE”);
printf(“\nstring is:%s”, ch);
strncat(ch,source,2);
printf(“\nResultant string is:%”,ch);
}
Output
Source string is: Rohtak
string is: DDE
Resultant string is: DDE RO
6.10.5 Copying Strings
For copying strings, we have the strcpy( ) function defined in <string.h> header file. The strcpy( )
function works almost like a string assignment operator. It takes the general form :
strcpy(str1, str2);
which assigns the contents of str2 to str1 where str2 may be either a string variable or a string
constant. For example, the statement
strcpy(name, “ram”);
86 Programming in C and Numerical Analysis

assigns the string “ram” to the string variable name. The size of the array str1 should be large enough
to accommodate the contents of the assigned string str2.
Strncpy( ) Function Remarks
The function strncpy copies only the left most n characters of the source string to the target string
variable. This function takes three parameters and has the general form :
strncpy (str1, str2, n);
Since, the n left most characters of str2 may not include the terminating null character, therefore
we have to place it explicitly at the (n+1)th position of ster1 as shown below:
str1[n+1] = ‘\n’;
Now, the string str1 is a proper string.
Program to show the use of strncpy function
#include <stdio.h>
#include <string.h>
void main ( )
{
char str[10];
char str1[] = “Deepak";
strncpy(str, str1, 3);
str[3] = ‘\0’;
printf(“The contents of variable string are: %s”, str);
}
Output
The contents of variable string are: dee
6.10.6 Comparison of string
C does not permit the direct comparison of strings, i.e., the statements like
if (name1 = = name2)
if (name1 = = “ram”)
are not valid. To compare two strings, it is necessary to compare strings character by character. The
comparison is done until there is a mismatch or one of the strings terminates. However, we have a
useful library function strcmp( ) for this purpose.
Strcmp( ) Function
The strcmp( ) function compares two strings passed to it as arguments and returns a value zero if
they are equal. If they are not equal, it returns the numeric difference between the first non-matching
characters in the strings. It has the general form :
strcmp(str1, str2);
where str1 and str2 are either string variables or string constant. For example :
strcmp(name1, name2);
strcmp(name1, “ram”);
strcmp(“ram”, “sham”);
for example the statement
strcmp(“neeraj”, “Nilesh”);
returns a value of 4 which is the difference between the ASCII value of ‘e’ and ‘i'. If the value is
negative, str1 comes alphabetically before str2.
Strncmp( ) Function
A variation of the strcmp function is the function strncmp( ). This function takes three parameters
and has the general form:
strncmp(str1, str2, n);
The function compares the left most n characters of str1 to the str2 and returns :
Array, String and Structure 87

(a) 0, if the strings are equal


(b) negative number, if the first non-matching character of str1 comes before the character of str2
at the same position, alphabetically.
(c) positive number, otherwise
Remarks Program to illustrate use of strcmp and strncmp functions
#include <stdio.h>
#include <string.h>
void main ( )
{
char string1[] = “health”;
char string2 [] = “heal”;
int n;
n = strcmp(string1, string2);
if(n = = 0)
printf(“The two strings are not same.”);
n = strncmp(string1, string2, 4);
if(n = = 0)
printf(“\nThe first four characters are same.”);
else
printf(“\nThe first four characters are not same.”);
}

Output
The two strings are not same.
The first four characters are same.

6.11 STRUCTURES AND UNIONS


We have seen that arrays can be used to represent a group of data items that belong to the same
type. However, we cannot use the array if we want to represent a collection of data items of different
types using a single name. C supports a constructed data type known as structures, a mechanism for
packing data of different types. For example, it can be used to represent a set of attributes, such as
student_name, roll_number and marks. The concept of a structure is analogous to that of a ‘record’ in
many other languages. More examples of such structures are :
time : seconds, minutes, hours
date : day, month, year
book : author, title, price, year, ISBN_number

6.11.1 Defining a structure


The general syntax of declaring a structure is :
struct <name>
{
data_type member1;
data_type member2;
……………………..
data_type membern;
}
<struct variables>;
where <name>  is the name of the structure i.e., name of the new data type. The keyword struct and
<name> are used to declare structure variable(s). It is also known as the structure tag.
<struct variable>  name(s) of structure variables.
88 Programming in C and Numerical Analysis

The individual members of a structure can be ordinary variables, array, or other structures. The
member names within a particular structure must be distinct from one another, though a member
name can be the same as the name of a variable defined outside of the structure.
Example : Remarks
struct complex
{
float real;
float Imaginary;
} comp;
The C compiler automatically allocates sufficient memoty to store all the elements that constitute
the structure. Figure 1 show how comp appears in memory

real 4 bytes

Imaginary 4 bytes

Figure 1 : The comp structure in memory.


The structure variable can also be declared as :
struct employee
{
int empl_no;
char name[30];
char Name_father[25];
char deptt[20];
};
struct employee emp;
Thus, emp is a variable of type employee. In other words, emp is structure type variable whose
composition is identified by the tag employee.
When we declare a structure, a data type is defined, that is no memory space is reserved.
The C compiler automatically allocates sufficient memory to store all the elements that constitute
the structure, when we declare structure variable. All the members of the structure are stored in
contiguous memory locations in the order of their declaration.
More than one variables can also be declared at the same time.
6.11.2 Arrays Versus Structures
Both the arrays and structures are called structured data types as these provide a mechanism that
helps us to access and manipulate data in a very simple manner. The following table gives the
differences between arrays and structures :
Sr. No. Array Structure
1. An array is a collection of Structure can have elements of
homogeneous elements i.e., same different types.
type.
2. An array is a derived data type. A structure is a user-defined data
type.
3. An array behaves like a built-in data A structure is designed and declared
type. It is done by first declaring an first. After this the structure
array variable and then using it. variable(s) of that type are declared
and used.
Array, String and Structure 89

6.11.3 Declaring structure variables


After defining a structure format we can declare variables of that type. A structure variable
declaration is similar to the declaration of variables of any other data types. It includes the following
elements :
Remarks 1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.
Once the composition of the structure has been defined, individual structure type variables can be
declared as follows:
struct tag var_1, var_2, var_3,….,var_n;
for example, the complete structure declaration might look like
struct book_card
{
char title[30];
char author[20];
int ISBN_number;
int year;
};
struct book_card card1, card2, card3;
The last statement declares card1, card2, and card3 as variables of type book_card.
6.11.4 Accessing structure members
Each member of a structure variable can be accessed by following the variable name with a dot
(period) and the member name. The period is the structure member operator or simply the dot
operator. For example, the four members of structure variable card can be referred in a program in
many different ways like
card1.author = “Deepak”;
strcpy(card1.title, “Welcome to MDU”);
y = card1.ISBN_number;
card1.year = 2006;
Each member can have a value of the appropriate type assigned to it, and it can be used like an
ordinary variable. The members of a structure must be accessed directly and explicitly. The dot
operator following the structure variable name can be followed only by a member name and not by a
string variable containing the name of a member.
6.11.5 Structure initialization
Like any other data type, a structure variable can be initialized at compile time.
void main ( )
{
struct
{
int weight;
float height;
}
student = (30, 50, 60);
…….
…….
}
90 Programming in C and Numerical Analysis

This assigns the value 30 to student.weight and 50.60 to student.height. There is a one-to-one
correspondence between the members and their initializing values.
A lot of variation is possible in initializing a structure. The following statements initialize two
structure variables. Here, it is essential to use a tag name.
void main ( ) Remarks
{
struct record
{
int weight;
float height;
};
struct record student1 = {30, 50.60};
struct record student 2 = {20, 30.10);
…….
…….
}
Another method is to initialize a structure variable outside the function as shown below :
struct record
{
int weight;
float height;
} student1 = (30, 50.60);
void main ( )
{
struct record student2 = (20, 30.10);
……
……
}

6.11.6 Copying and comparing structure variables


If there are two variables of the same structure type, they can be copied in the same way as
ordinary variables. if card1 and card2 are variables of the same the same structure, then the following
statements are valid :
card1 = card2;
card2 = card1;
However, the statement such as :
card1 = card2;
card1 != card2;
are not permitted to compare them. C does not permit any logical operations on structure variables. In
case we need to compare them, it can be done by comparing each and every member individually, as
illustrated by the following program.
Program to illustrate the comparison of structure variables
#include < stdio.h>
struct date
{
int day; /*declaring structure members*/
int month;
int year;
};
Array, String and Structure 91

void main ( )
{
int x;
stuct date date1 = (10, 02, 1985);
stuct date date2 = (14, 02, 1985);
struct date date3, date4;
Remarks if (date1.day == date2.day) /*checking individual values*/
{
if(date1.month == date2.month)
{
if(date1.year == date2.year)
printf(“\ndate1 and date2 are equal”);
else
printf(“\ndate1 and date2 have different years”);
}
else
printf(“\ndate1 and date2 have different months”);
}
else
printf(“\ndate1 and date2 have different days”);
date3 = date2;
printf(“\ndate3: day = %d month = %d year = %d”, date3.day, date3.month,
date3.year);
date4.day = date1.day; /*assigning individual values*/
date4.month = date1.month;
date4.year = date1.year;
printf(“\ndate4: day = %d month = %d year = %d”, date4.day, date4.month,
date4.year);
}
Output
date1 and date2 have different months
date3: day = 14 month = 02 year = 1985
date4: day = 10 month = 02 year = 1985
6.12 STRUCTURES AND ARRAYS
Arrays are collection of analogous elements and structures combine dissimilar elements
together. Both of these allow several data elements to be treated collectively and are C derived types.
Arrays and structures can be tied together to form complex data types. There may be an array of
structures and an array may be an element of a structure.
6.12.1 Arrays of structures
Array is a collection of similar elements. An array having structures as its elements is called an
array of structures. First a structure is declared and then an array of structures can be declared for
storage. For example,
struct employee
{ int empl_no;
char name[30];
char designation[25];
char deptt[20];
} emp[10]; /*array of structures declared*/
92 Programming in C and Numerical Analysis

Using the above statement 10 set of variables are arranged as defined by the structure employee.
For accessing any structure, index is used. For example, to read the employee number of structure
3, we write
scanf(“%d”, &emp[2].empl_no);
as you know that indexing in arrays in C starts at 0.
struct employee emp[20]; Remarks
For reading the date for 12th employee (i.e., emp[11], since the subscript begin with 0), we write
scanf(“%d”,&emp[11].empl_no);
fflush(stdin); /*empty the buffer*/
gets(emp[11].name); /*for accepting multiword string*/
gets (emp[11].designation);
gets(emp[11].deptt);
scanf(“%d”,& emp[11].address.houseno);
fflush(stdin);
gets(emp[11].address.area);
gets(emp[11].address.city);
gets(emp[11].address.state);
gets(emp[11].address.pincode);
scanf(“%f”, & emp[11].basic_pay);

6.12.2 Arrays within structures


C permits the use of arrays as structure members. We have already used arrays of characters
inside a structure. Similarly, we can use single-dimensional or multi-dimensional arrays of type int or
float. For example, the following structure declaration is valid.
struct marks
{
int number;
float subject[3];
} student[2];
Here, the member subject contains three elements, subject[0], subject[1] and subject[2]. These
elements can be accessed using appropriate subscripts. For example, the name
student[1].subject[2];
would refer to the marks obtained in the third subject by the second student.
Write the program using an array member to represent the three subject
main ( )
{
struct marks
{ int sub[3];
int sum;
};
struct marks student [3] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
struct marks sum;
int i, j;
for (i = 0; i <=2; i++)
{
Array, String and Structure 93

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


{
student[i].sum += student[i].sub[j];
sum.sub[j] += student[i].sub[j];
}
Remarks Sum.sum += student[i].sum;
}
printf(“STUDENT sum\n\n”);
for(i = 0; i <=2; i++)
printf(“Student[%d] %d\n”, i+1, student[i].sum);
printf(“\nSUBJECT sum\n\n”);
for(j = 0; j<=2; j++)
printf(“Subject-%d %d\n”, j+1, sum.sub[j]);
printf(“\nGrand sum = %d\n”, sum.sum);
}

6.12.3 Structures within structures


Structures within a structure means nesting of structures. Nesting of structures is permitted in C.
Let us consider the following structure defined to store information about the salary of employees.
struct salary
{
char name;
char department;
int basic_pay;
int dearness_allowance;
int house_rent_allowence;
}
employee;
This structure defines name, department, basic pay and three kinds of allowances. We can group
all the items related to allowance together and declare them under a substructure as shown below:
struct salary
{
char name;
char department;
struct
{
int dearness;
int house_rent;
int city;
}
allowance;
}
94 Programming in C and Numerical Analysis

employee;
The salary structure contains a member named allowance, which itself is a structure with three
members. The members contained in the inner structure namely dearness, house_rent and city can be
referred to as:
employee.allowance.dearness Remarks
employee.allowance.house_rent
employee.allowance.city
An inner-most member in a nested structure can be accessed by chaining all the concerned
structure variables (from outer-most to inner-most) with the member using dot operator. The
following are invalid:
employee.allowance(actual member is missing)
employee.house_rent(inner structure variable is missing)
An inner structure can have more than one variable. The following form of declaration is legal:
struct salary
{
…….
struct
{
int dearness;
……
}
allowance,
arrears;
}
employee[100];
The inner structure has two variables, allowance and arrears. This implies that both of them have
the same structure template. Note the comma after the name allowance. A base member can be
accessed as follows:
employee[1].allowance.dearness
employee[1].arrears.dearness
6.13 STRUCTURES AND FUNCTIONS
There are several different ways to pass structure-type information to and from functions.
Structure members can be passed individually or the entire structures can be passed to functions. The
method of passing structures depends on type of transfer (i.e., whether a complete structure or its
members have to be passed0 and on the version of C used.
Individual structure members can be passed to a function as arguments in the function call like all
other ordinary variables. A single structure member can be returned via the return statement.
To pass the whole structure to the function, a copy of the entire structure is passed to the called
function. Since a copy is passed, any changes to structure members are not reflected in the original
structure 9or in the calling function). This necessitates the requirement to return the entire structure
back to the calling function. The general format of sending a copy of a structure to the called function
is
function_name(structure_variable);
Array, String and Structure 95

The called function takes the following form


datatype function_name(struct_type struct_name)
{
………….
………….
return(expression);
}

Remarks The called function must declare its type appropriate to the data type that it is expected to return.
For example, while returning entire structure, return type must be declared as struct with an
appropriate tag name. Further, the expression in the return statement may be any simple variable,
structure variable or an expression using simple variables.
The following program illustrates this concept:
Program to illustrate passing of structures of functions
#include <stdio.h>
#include <string.h>
struct student
{
char name [20];
int age;
};
void func1(struct student s)
strcpy(s.name, “Isha”);
s.age=32;
printf(“\n\nInside func1\nName: %s\nAge: %d”, s.name,s.age);
}
struct student func2(struct student s)
{
strcpy(s.name, “Isha”);
s.age = 32;
return(s);
}
void main ( )
{
struct student s1=(“Varun”, 21), s2;
clrscr( );
/*Display structure values */
printf(“In main ( ), S1 is …\n Name: %s\Age: %d, s1.name, s1.age);
/* Pass structure variable to function which does not return anything*/
func1(s1);
/* After function call, changes made to structure members are not reflected here */
printf(“\nAfter func1( ), s1 is …\nName: %s\nAge: %d”, s1.name,s1.age);
/* pass structure variable to function that returns a structure variable */
s2 = func2(s1);
/* After function call, changes are reflected in the structure variable accepted*/
printf(“\n\nAfter func2(), s1 is…\nName: %s\nAge: %d”, s1.name,s1.age);
printf(“\n\nAfter func2(), s2 is…\nName: %s\nAge: %d”, s2.name,s2.age);
}
96 Programming in C and Numerical Analysis

Output
In main ( ), s1 is…
Name: Varun
Age: 21

Inside func1 ( ) Remarks


Name: Isha
Age: 32

After func1 ( ), s1 is…


Name: Varun
Age: 21

After func2 ( ), s1 is…


Name: Varun
Age: 21

After func2 ( ), s2 is…


Name: Isha
Age: 32

6.14 UNIONS
Unions, like structures, contain members whose individual data types may differ from one
another. However, unlike structures, all the members of a union use the same memory location.
Although, a union may contain members of different type, it can handle only one member at a time.
Like structures, a union is declared as follows :

union item
{
int a;
float b;
char c;
} item1;

The compiler allocates memory equal to the size of the largest variable type in the union. To
access a union variable, we again use the dot operator. Thus,
item1.c
item1.b

are valid member variables. During accessing, we must be sure that we are accessing the member
whose value is currently stored. For example,

item.a = 10;
item2.b = 18.963;
printf(“%d”,item1.a);
Array, String and Structure 97

produces an errorneous result since the memory contains a float (last stored value) and the format
specifier used is that of an integer.

A union may be a member of a structure, and a structure may be a member of a union. Moreover,
C permits free mixing of structures and unions with arrays.
Remarks A union variable can be initialized during its declaration. However, only one member of a union
can be assigned a value at any one time. Most compilers assign this value to the first member of the
union.

For example, the declaration


item1.a = {10};
is valid while the declaration
item1.b = {12.6};

is not permitted in C since the first member of type int. Other member can be initialized individually
be either assigning values or accepting input from the keyboard.

Keywords : Array, string, structure, union etc.


Summary : In this unit, student learn how deal with various data types which may be same or
different. We also study how to deal long data and students know difference between array and
structure.
Remarks

CHAPTER – VII
POINTERS AND FILE IN C
7.0 STRUCTURE
7.1 Introduction
7.2 Objective
7.3 The Concept
7.4 Files in C
7.1 INTRODUCTION
One of the major features that distinguishes the C language from most other high-level language
is the abundant use of pointers. A pointer is a variable that represents the location (address rather than
the value) of a data item, such as a variable or an array element. Since program instructions and data
are stored at memory locations (or memory addresses), pointers can be used to access and manipulate
data stored in the memory. Pointers are used frequently in C as they offer a number of benefits to the
programmers, such as :
1. Pointers are more efficient in handling arrays and data tables.
2. Pointers permit references to functions thereby facilitating passing of functions as arguments
to other functions.
3. Pointers allow C to support dynamic memory management.
4. pointers provide an efficient tool for manipulating dynamic data structures such as structures,
linked lists, queues, stacks and trees.
5. Pointers can be used to return multiple values from a function via function arguments.
6. Pointers increase the execution speed and thus reduce the program execution time.
7. Pointers reduce length and complexity of programs.
Pointers are undoubtedly one of the most distinct and exciting feature of the C language.
7.2 OBJECTIVE : At the end of this unit student should be able to know
1. Initialization, declaration, implementation, comparison of pointers.
2. We learn how pointers use the memory.
3. Opening, reading, combining, closing, copying of files.
7.3 THE CONCEPT
A pointer is a variable that represents the location (rather than the value) of a data item, such as a
variable or an array element. Whenever we use a variable, it is stored in memory. Whenever the
program has to access that variable, it retrieves it from memory. Each memory location has a numeric
address associated with it. The high level languages like C enable the programmer to refer to memory
locations of variables by name, but the compiler must translate these names into addresses. This
process is automatic, so the programmer need not be concerned with it. However, C enables the user
to refer to these addresses indirectly, in order to manipulate the contents contained in these addresses
or memory locations.
The memory addresses are global to all functions, while variable names are local and meaningful only
within the functions in which they are declared. A function can pass the address of a local variable to
another function and the second function can use this address to access the contents of the first
function’s local variable.
Passing addresses does not violate the rules of modular programming. The addresses are passed
only to the functions that need to access those memory locations. Passing a local variable’s address is
analogous to passing a key; only the functions possessing the key can access the variable in question,
so some measure of protection is involved.
Pointers and File in C 99

Remarks
At any given moment in a program’s execution, each existing variable has a unique address
associated with it. When the functions finish execution, the declared local variables disappear. The
memory location occupied by such a local variable is made free and can be reused later by the
program.
7.3.1 THE ADDRESS OPERATOR (&)
The actual location of a variable in the memory is system dependent and is not available
immediately. Then how can the address of a variable be determined. Actually, we have been
accessing the addresses all along. The ampersand(&) preceding a variable name returns the address of
the variable with it. For example, in the call to a scanf function we used the ampersand(&) followed
by the variable name to access the address of that variable. This operator is known as the address
operator. For example, the statement
x = &a;
would assign the address of variable a to the variable x. The & operator can also be remembered as
‘address of’ operator.
The & operator may precede only a variable name or an array element; never a constant, an
expression or the unsubscripted name of an array. It can be used with any item that can be placed on
the left side of an assignment operator.
7.3.2 DECLARING POINTERS
Addresses themselves can be stored in variables. Addresses are a separate data type in C, distinct
from the other types introduced so far. There are, infact, several types of addresses. The address of an
integer variable is of a different type from that of a character variable. The declaration of a pointer
variable has the following form:
data_type *pointer_name;
For example, a variable that can hold the address of an integer can be declared as follows:
int *ram; /* integer pointer */
The asterisk (*) is not part of the variable name; rather int * (“pointer to int”) is the data type of
variable ram. If we declare the following :
int *BA, BSc;
only BA would be the type int*, while BSc would be simply an integer variable. The type of the item
pointed by a pointer variable is also referred as the target type. For example, target type of in* is int.
Pointer variables are named like any other variables. Since the asterisk is not part of the name, the
following example is illegal because it attempts to declare the same variable twice with two different
types.
int ram; /* ram is of type ‘int’ */
int *ram; /* ram is of type ‘int*’ */
When a variable is declared as a pointer, it is not automatically initialized to any value. In this
respect, it is just like any other variable. Initially, a pointer does not point to anything or it contains
some unknown value or garbage. Since the compiler does not detect these errors, the programs with
uninitialized pointers produce errorneous results. It is, therefore, important to initialize pointer
variables carefully before they are used in a program. To assign an address to a pointer, the
programmer must assign it a value. For example,
int BSc;
int *BA; /* declaration */
BA = &BSc; /* initialization */
may be interpreted “assign the address of BSc, to BA. We can also combine the initialization with the
declaration, i.e., pointers can also be initialized as
int BSc;
int *BA = &BSc; /* declaration as well as initialization */
100 Programming in C and Numerical Analysis

The pointer variable can be defined with an initial value of NULL or 0(Zero). That is, the Remarks
following statements are valid.
int *a = NULL;
int *a = 0;
However, except NULL and 0 no other constant value can be initialized to a pointer variable.
Using cast operator we can assign the address to a pointer variable of a different target type. For
example. If c is of type char* and d is of type int, the following is perfectly valid:
c = (char *) &d;
In this statement, the address of integer variable d is converted from type int * to type char * and
assigned to c.
Pointers are quite flexible. We can make the same pointer variable to point to different data
variables (but of same data type) in different statements and we can also use different pointers to the
point to the same data variable. For example, p1 a
int a, b, c, *p1, *p2, *p3;
p1 = &a; /* p1 points to a */
p1 = &b; /* p1 points to b */ p1 b
p1 = &c; /* p1 points to c */
p1 = &a /* point p1 points to a */ p1 c
p2 = &a /* point p2 points to a */ p2
p3 = &a /* point p3 points to a */ p1 p3

The question arises as to why there are so many types of pointers, like pointers to int, pointers to
char and so on. Actually every type occupies different amount of memory. Like on most systems, int
occupies two bytes while char occupies one byte. Therefore, every data type must have a different
pointer. However, we do have a generic pointer that can represent any pointer type. All pointer types
can be assigned to a void pointer and a void pointer can be assigned to any pointer without casting. A
void pointer is created as follows :
void *p; /* p is a void pointer */
The void pointer has no object type and hence it cannot be dereferenced.
7.3.3 The Indirection Operator
Once the address of variable i has been assigned to the pointer variable j, then j can be used to
manipulate the contents of i. This is done by using another unary operator * called as the indirection
operator. Consider the following program :
Program : An introduction to pointers
#include <stdio.h>
void main ( )
{
int i = 20;
int *j, k; /* j is a pointer to integer */
j = &I; /* Intialize j to address of variable i */
k = *j; /* Assign value pointed by j to k */
*j = 4;
printf(“i = %d, *j = %d, k = %d\n”, i,*j, k);
}
Output
i = 4, *j = 4, k = 20
Pointers and File in C 101

Remarks 7.3.4 Pointers to Pointers


C allows to make a pointer to point to another pointer, thus creating a chain of pointers. A
variable that is a pointer to a pointer must be declared using additional indirection operator symbols in
front of its name. For example,
int **p2;
This declaration tells the compiler that p2 is a pointer to a pointer of int type. This is known as
multiple pointers or multiple indirections. It is worth mentioning that p2 is not a pointer to an integer
but rather a pointer to a pointer pointing to an integer. In fact, C allows pointers to pointers, pointers
to pointers to pointers and so forth.
The target value pointed indirectly by the pointer to a pointer can be accessed by applying the
indirection operator twice. For example, the statements :
int x, *p1 = &x, **p2 = &p1;
x = 100;
printf(“%d”, **p2);
outputs the value 100. Here, p1 is declared as a pointer to an integer and p2 as a pointer to pointer to
an integer.
7.3.5 Pointer Arithmetic
On most machines, memory addresses are dimply integers, so a pointer value may be cast
automatically into an int or some other compatible type. However, pointers are somewhat different
from integers in the way calculations or arithmetic operations are performed on them.
The addition or subtraction of a pointer and an integer is one of the few arithmetic operations
allowed on pointers. When an integer is added or subtracted to a pointer of any type, the result is a
pointer of the same type. It is not the case of a mixed mode, because the two operands are supposed to
be of different types and no casting is done. For example, the following statements are perfectly valid
in C :
++p;
p++;
p ;
 p;
p = p + 4;
p = p  5;
Each expression results in an address that is located some distance from the original address
pointed by p. The exact distance is the product of integer value and the number of bytes occupied in
the memory by the data type pointed by the pointer p. That is, if we increment a pointer, its value is
increased by the ‘length’ of the data type that the pointer points to. This length is called the “scale
factor”. FOr example, if p1 is a pointer to integer with an initial value 3600 then p1++ results in value
of p1 changing to 3602 (not 3601 but 3600+1*2, where 2 is the size of an integer, i.e., the scale
factor). Similarly p1+4 now results in the value of p1 to become 3610 (3602+4*2). The number of
bytes used to store various data types is system dependent and can be found by using the sizeof
operator. It should be understood, however, that this new address will not necessarily represent the
address of another data item, particularly if the data item stored between the two addresses involves
different data types.
The other possible operation is the subtraction of a pointer from a pointer if both pointers points
to the same data type. The result is an integer which indicates the number of words or bytes separating
the two pointers. A pointer subtraction resulting in a negative value is not supported on some
computers, but such a subtraction is rarely required.
102 Programming in C and Numerical Analysis

The relational operators like >, <, = =, != can also be used on pointers pointing to the same data
type. Such comparisons are useful when two pointer variables point to elements of the same array.
Further, a pointer variable can be compared with zero (which is the NULL pointer).
Remarks
7.3.6 Pointers and Arrays
Pointers are intimately associated with arrays. The unscripted name of an array is evaluated as a
constant pointer. Therefore, if arr is an integer array and i is the integer variable, then the statement
arr = &I;
is illegal in C since a constant cannot be placed to the left of an assignment operator.
The name of an array points to its first element or the zeroth element. That is, if we declare p as
an integer pointer, then we can make the pointer p to point to the array x by the following assignments
p = x; /* x is an integer array */
or p = &x[0];
The elements of an array are stored contiguously (adjacent to one another) and all are of the same
type. So every value of x can be accessed using p++ to move from one element to another. For
example, if an array x of type int has base address (address of first element) 3000 and assuming that
each integer requires two bytes, the relationship between p and x is as follows :
p=x (=&x[0]=3000)
p+1=&x[1] (=3002)
p+2=&x[2] (=3004)
p+3=&x[3] (=3006)
p+4=&x[4] (=3008)
and so on. The address of an element is calculated using its index and scale factor of the data type. For
example,
address of x[4] = base address + (4*scale factor of int)
= 3000+(4*2) = 3008
Thus, use of pointers provides a convenient method of handling arrays, instead of using array
indexing. The pointer accessing method in much faster than the array indexing. The value of x[3] can
be conveniently referred by using *(p+3).
Program to compute sum of all elements stored in an array
#include <stdio.h>
void main ( )
{
int i, *p;
int x[10];
printf(“\nEnter 9 elements of the array :\n);
for(i = 0; i < 9; i++)
scanf(“%d”, &x[i]); /* Inputting array elements */
p = x;
for(i = 0; i < 9; i++)
{
printf(“x[%d] %d %u \n”, i,*p, p);
sum = sum + *p; /* Accessing array element */
p++;
}
printf(“\n &x[0] = %u”, &x[0]);
printf(“\n p now points to %u”, p);
}
Output
Pointers and File in C 103

Enter 9 elements of the array :


5 10 15 20 2 3 4 5 6
x[0] 5 30004
x[1] 10 30006
x[2] 15 30008
Remarks x[3] 20 30010
x[4] 2 30012
x[5] 3 30014
x[6] 4 30016
x[7] 5 30018
x[8] 6 30020
&x[0] = 30004
p now points to 30022
In this program, incrementing an array pointer causes it to point to the next element, so we need
to increment p by one every time we go through the loop.
Pointers can be used with two dimensional arrays as well. The name of a two dimensional array is
also evaluated as a pointer in C. Let us consider a two dimensional array ‘a’. The base address of the
array a is &a[0][0] and starting at this address, the compiler allocates contiguous space for all the
elements row wise. That is, a two dimensional array can be regarded as an array of rows where each
row is itself an array of columns. Suppose we have to represent the element a[i][j]. Then, the
unsubscripted name a points to the first row and first column, that is, the address of a[0][0]. Each row
is an array of columns. The ith the two-dimensional array a is represented as *(p+i), where p = a(or p =
&a[0][0]).
Now, the ith row is an array of column with starting address *(p+i). Its j th elements or jth column is
given by (*(p+i)+j) and therefore its contents are given by :
*(*(p+i)+j)
Thus a[i][j] can be accessed as *(*(p+i)+j).
7.3.7 Pointers and Character Arrays
Strings are supported as character arrays in C. Therefore, pointer variables of type char can be
used to create strings. For example,
char *str=”Priya”;
This creates a string for the literal and then stores its address in the pointer variable str. So,
pointer str points to the first character of string. A string pointer can also be given run time
assignment like
char *str;
*str = “Priya”;
However, the above statement is not a string copy operation because the variable str is a pointer,
not a string. The contents of the string str can be printed like normal strings using printf or puts
functions, like
printf(“%s”, str);
or puts(str);
Since str is the pointer to the string and also the name of the string, therefore, the indirection
operation * is not used.
Program to find length of a string
#include <stdio.h>
void main ( )
{
104 Programming in C and Numerical Analysis

char *name;
int length;
char *lptr;
name = “Rajat”;
Remarks
lptr = name;
printf(“%s”, name);
while(*lptr != ‘\0’)
lptr++;
length = lptr  name;
printf(“\n length of the string = %d”, length);
}
Output
Rajat
length of the string = 5
A string is always terminated by a NULL character, therefore, the pointer to string can be
incremented till it encounters a NULL character. Then the difference between the final address and
base address gives the length of the string.
7.3.8 Array of Pointers
Pointers are just another data type in C. So, it is perfectly valid to have an array of pointers. Such
an array of pointers can be used to handle a table of strings. In array representation, fixed size of rows
and columns have to be declared resulting in reservation of a fixed storage of memory. However,
strings are rarely of equal lengths, therefore, instead of making each row of a fixed number of
characters (like in normal array representation), we can make it a pointer to a string of varying length.
Consider the following statement :
char *a[5];
It declares a as an array of 5 character pointers. Like explained above, each char pointer can hold
a string. Thus, a can hold five strings, referred by a[0] to a[4].
7.3.9 Pointers as Function Arguments
Pointers are often passed to a function as arguments. When we pass addresses to a function, the
parameters receiving the addresses should be pointers. The process of calling a function using
pointers to pass the addresses of variables is known as call by reference. The process of passing the
actual value of variables is known as call by value. Passing addresses of variables allows data items
within the calling portion of a program to be accessed by a function, altered within the function, and
then returned to the calling program in altered form.
Program to illustrate call by reference
#include <stdio.h>
void main ( )
{
int x;
void modify (int*);
printf(“Enter value of x :”);
scanf(“%d”, &x);
modify(&x); /* call by Reference */
printf(“\nValue of x after function call : %d”, x);
}
void modify(int *a)
{
*a = *a+20;
Pointers and File in C 105

}
Output
Enter value of x : 9
Value of x after function call : 29
When the function modify( ) is called, the address of the variable x and not its value is passed.
Inside modify, a is a pointer containing the address of variable x. The statement
Remarks *a = *a + 20;
Therefore, adds 20 to the contents of the address pointed by a, i.e., x is increased by 20.
When pointers are used as arguments to a function, some care is required with the formal
argument declarations within the function. The function parameters are declared as pointers. The
dereferenced pointers are used in the function body and when the function is called, the addresses of
variables are passed as actual arguments.
7.3.10 Function Returning Pointers
Pointers are a data type in C, so a function can also return a pointer to the calling function. For
example, consider the following program segment :
Program to evaluate larger of two numbers
int *larger(int*, int*);
void main ( )
{
int a, b, *p;
printf(“Enter values of a and b:”);
scanf(“%d %d”, &a, &b);
p = larger (&a, &b); /* function call */
printf(“The larger number is %d”, *p);
}
int *larger(int* x, int* y)
{
int *t;
if(*x > *y)
t = x; /* assign address of x to pointer t */
else
t = y; /* assign address of y to pointer t */
return t;
}
Output
Enter values of a and b: 9 3
The larger number is 9
The function larger( ) receives the address of the variables a and b, decides which one is larger
and then returns the address of its location. The return value is assigned to the pointer variable p is the
calling function which is then displayed. The address returned must be the address of a variable in the
calling function. Returning the address of a local variable is an error, since a local variable cannot be
accessed outside its scope.
7.3.11 Pointers to Functions
A pointer to a function can be passed to another function as an argument. This allows one
function to be transferred to another, as though the first function were a variable. If we call the first
function as the guest function and the second function as the host function, then the guest is passed to
host, where guest can be accessed. The host function can take different pointers (or different guest
functions) as its arguments.
106 Programming in C and Numerical Analysis

When the host function is called by the calling function, the host function can take different guest
functions as its arguments on successive calls. A pointer to a function can be declared as :
datatype (* fptr) ( );
This tells the compiler that fptr is a pointer to a function returning a value of type datatype.
However, it should be not be mixed with the statement.
datatype *gptr( ); Remarks
which declares gptr as a function whose return type is data type*, i.e., it returns a pointer to data type.
The function pointer can point to a specific function by simply assigning the name the function to
the pointer. For example,
double mul(int, int);
double (*p) ( );
p = mul;
declares p as a pointer to a function having return type double. Now, the pointer to a function p points
to the function mul. To call the function mul, the pointer p can be used with the list of parameters.
That is, the statement:
(*p) (x, y); /* Function call */
is equivalent to
mul(x, y);
A pair of parentheses is required around p since ( ) has higher precedence than *.
7.4 FILES IN C
7.4.1 Introduction to Files
Every program takes some data as input and generates processed data as output following the
familiar input output cycle. Many real life situations handle large volumes of data and in such
situations console oriented I/O operations such as scanf and printf pose two problems:
(i) It becomes cumbersome and time consuming to handle large volumes of data through terminal.
(ii) The entire is lost when either the program is terminated or the computer is turned off.
To deal with such problems, data must be written to or read from an auxiliary memory device like
hard disk, floppy disk, magnetic tapes etc. The data is stored on the memory device in the form of a
file. Thus, a file is a collection of related data stored at a particular location on the disk. Files allow us
to store information permanently and to access and alter that information whenever necessary.
Unlike other high level languages, C does not distinguish between sequential and random
access files. However, there are two distinct ways to perform file operations in C. The first one is
known as the low-level I/O or system-oriented I/O and is more closely related to computer’s operating
system. This method of performing file operations is more difficult to carry out and thus, a separate
set of functions accompanying library functions are required to process system oriented files.
The second method is referred to as the high level I/O operation or stream oriented I/O and uses
functions in C’s standard I/O library. Stream-oriented files are generally easier to work with and are
used more commonly.
The stream oriented files can further be divided into two subcategories. In the first category are
text files consisting of consecutive characters. These characters can be interpreted either as individual
data items or as components of strings or numbers. The manner in which these characters are
interpreted depends upon the library functions used or by its format specifiers.
The second category of stream-oriented files called as unformatted files, does not deal with
characters but instead organizes data into blocks of information. These blocks represent more
complex data structures such as arrays and structures. We have a separate set of library functions for
this type, which provide single instructions that can transfer entire arrays or structures to and from
files.
In this chapter we shall discuss stream-oriented files and the library functions supporting them.
Pointers and File in C 107

7.4.2 THE FILE TYPE


The header file stdio.h also defines a new data type call FILE (all letter capitalized). The data type
FILE is used to describe various features of a file. Each file used in a program must have a pointer
associated with it. It establishes a buffer area, where information is temporarily stored while being
transferred between the computer’s memory and the data file. This buffer area allows information to
be read from or written to the file more rapidly. The buffer area is established as
FILE *ftpt;
Remarks where fptr is a pointer variable called a stream pointer or simply a stream. It indicates the beginning
of the buffer area. Two constants of the type FILE* are defined in stdio.h. These are stdin and stdout
representing standard input and standard output respectively.
A constant stderr is also defined to represent the standard error file. The functions using FILE* as
a parameter can use these constants to operate on standard input or output.
7.4.3 Opening and Closing a File
A file must be opened before it can be accessed. This associates the filename with the buffer area
(or stream). When we open a file, we must specify what we want to do with the file. For example, we
may write data to the file or read the already existing data. The library function fopen is used to open
a file. This function is typically written as follows:
fptr = fopen(“file-name”, “mode”);
where file-name and mode are strings that represent the name of the file and the manner in which the
file will be utilized, i.e., as a read only file, a write only file or a read/write file, respectively. The
name chosen for filename must be consistent with the rules for naming files in the computer’s
operating system. The mode can be any one of the following :

TABLE 1
Mode Specifications
Mode Meaning
r Open an existing file for reading only.
w Open a new file for writing only. If a file with the specified
file name exists currently, it is discarded and a new file is created in its
place.
a Open an existing file for appending (i.e., for adding new information at
the end of the file). A new file is created if the file does not exist
currently.
r+ Open an existing file for both reading and writing.
w+ Open a new file for both reading and writing. If a file (with specified file
name) exists currently, it is discarded and a new file is created in its
place.
+
a Open an existing file for both reading and appending. A new file is
created if the file with specified name does not exist.
If the file cannot be opened, like when an existing file is not found, a NULL value is returned.
Finally, a file must be closed as soon as all operations on it have been completed. This can be
accomplished with the library function fclose which has the syntax.
fclose (fptr);
Although all files are closed automatically at the end of a program execution, it is a good
programming habit to close a file explicitly.
The following statements appear in a program that uses files :
FILE *fptr;
fptr = fopen(“sample_text”, “w”); /* open file */
……….
108 Programming in C and Numerical Analysis

fclose(fptr); /* close file */


……….
Here, the file named sample_text is first opened for writing and after performing the desired
operations, it is closed.

Remarks
7.4.4 The getc and putc Functions
The simplest file I/O functions are getc and putc functions. These functions are analogous to
getchar and putchar, except that they can operate on streams other than the standard input and output.
Assuming that a file is opened with mode ‘w’ and file pointer fptr1 the statement
putc(c, fptr1);
writes the character contained in the character variable c to the file associated with file pointer fptr1.
Similarly, getc function is used to read a character from a file in read mode simply as,
c = getc(fptr2);
It reads a character from the file whose file pointer is fptr2. These functions handle one character
at a time and move by one character position for every operation. The getc returns an end-of-file
marker (EOF), when end of the file is encountered. The EOF character is usually control-Z (or it can
be control-D in some other systems). Consider the following program :.
Program to display getc and putc functions
#include <stdio.h>
void main ( )
{
FILE *fpt1;
char c;
printf(“Data input : \n”);
fpt1 = fopen(“Sample”, “w”); /*open Sample in write mode */
while((c = getchar( ) ) != EOF) /* Read characters from keyboard */
putc(toupper (c), fpt1);
flclose(fpt1); /* Close the file */
printf(“\nData output: \n”);
fpt1 = fopen(“Sample”, “r”); /* Reopen in read mode */
while((c = getc(fpt1)) != EOF) /* Read from file */
printf(“%c”, c); /* Display character on screen */
fclose(fpt1); /* Close the file */
}
Output
Data Input :
A simple program to read and write to a file ^z
Data Output :
A SIMPLE PROGRAM TO READ AND WRITE TO A FILE
The program opens a file named sample in write mode. It accepts input from the user character by
character using a while loop, until EOF is encountered. Each character read as input is converted to
uppercase by using the toupper ( ) library function and written into the file. Then this file is closed and
reopened in read mode. The program then reads the file character by character and displays its
contents on the screen.
Pointers and File in C 109

On encountering the EOF marker, reading from file is terminated. It is necessary to test for EOF
condition. Any attempt to read past the end-of-file might either cause the program to terminate with
an error or result in an infinite loop situation.
7.4.5 The getw and putw Functions
The getw and putw function are similar to getc and putc functions and can accept only integer
data. The general forms of getw and putw are
putw(integer, fpt1);
getw(fpt1);
The following program illustrates their use :
Program to use getw and putw functions
Remarks #include <stdio.h>
void main ( )
{
FILE *fpt1, *fpt2, *fpt3;
int number, i;
printf(“Enter data for DATA file:\n”);
fpt1 = fopen(“DATA”, “w”); /* Create DATA file */
do
{
scanf(“%d”, &number);
putw(number, fpt1);
}
while(number!= 1);
fclose(fpt1); /*close the file */
fpt1 = fopen(“DATA”, “r”);
fpt2 = fopen(“ODD”, “w”);
fpt3 = fopen(“Even”, “w”);
printf(“\nContents of DATA file: \n”);
while((number = getw(fpt1))!=EOF) /*Read from DATA file */
{
if (number%2 = = 0)
putw(number, fpt3); /*Write to EVEN file */
else
putw(number, fpt2); /* write to ODD file * */
printf(“%d”, number);
}
fclose(fpt1); /* Close the files */
fclose(fpt2);
fclose(fpt3);
fpt2 = fopen(“ODD”, “r”); /* Reopen ODD file */
fpt3 = fopen(“EVEN”, “r”); /* Reopen EVEN file */
printf(“\nContents of ODD file are: \n”);
while((number = getw(fpt2))!=EOF)
printf(“%d\t”, number); /* Display on screen */
printf(“\nContents of EVEN file are:\n”);
while((number = getw(fpt3))!= EOF) /* Read from EVEN file */
printf(“%d\t”, number); /*Display on screen */
fclose(fpt2);
fclose(fpt3);
110 Programming in C and Numerical Analysis

}
Output
Enter data for DATA file :
12 11 14 20 139 45 56 78 90 81 2 1
Contents of DATA file :
12 11 14 20 139 45 56 78 90 81 2
Contents of ODD file are :
11 139 45 81
Contents of EVEN file are :
12 14 20 56 78 90 2
In this program a file named DATA is created using putw( ) which takes only integer values from Remarks
the terminal. The even values are written into file named EVEN and the odd values are written into
the file named ODD. When we type 1, the reading is terminated and the file is closed. The contents
of files ODD and EVEN are displayed using getw( ).
7.4.6 The fprintf and fscanf Functions
The functions encountered so far can handle only a single character at a time. However, C
provides two other functions, namely fprinf and fscanf, that can handle a group of mixed data
simultaneously.
The functions fprinf and fscanf are quite similar to printf and scanf functions except that they
work on files and take one more parameter fptr which indicates the stream or file pointer to be used.
The general form of fprintf function is
fprintf(fptr, “control string”, list);
where fptr is a file pointer associated with a file opened in write mode. The other two parameters
control string and list are similar to that of the printf function. For example,
fprintf(fpt1, “%s %d %f”, name, age, height);
Here, name is a string, age is an int variable while height is a float variable. The general format
for fscanf ( ) is
fscanf(fptr, “control string”, list);
This statement causes the reading of items in the list from the file pointed by the file pointer fptr,
according to the conversion specification provided by the control string.
For example :
fscanf(fptr2, ‘%s %d”, &item, &price);
Like scanf, fscanf also returns the number of items that are successfully read. When the end of file
is reached, it returns the value EOF.
Program to illustrate fprintf and fscanf functions
#include <stdio.h>
void main ( )
{
FILE *fpt1;
int i, age;
float height;
char name[10], filename[10];
printf(“Input file name:”);
scanf(%s”, filename);
fpt1 = fopen(filename, “w”);
printf(“Input data:”);
Pointers and File in C 111

printf(“\nName\tAge\tHeight\n”);
for(i = 1; i<=3; i++) /* Enter data from user to file */
{
fscanf(stdin, “%s %d %f”, name, &age, &height);
fprintf(fpt1, “%s %d %f”, name, age, height);
}
fclose(fpt1); /* Close file*/
fpt1 = fopen(filename, “r”);
printf(“\nData in input file :”);
Remarks printf(“\nName\tAge\tHeight\n”);
for(i = 1; i<=3; i++)
{
fscanf(fpt1, “%s %d %f”, name, &age, &height);
fprintf(stdout, “\n%s\t%d\t%f”, name, age, height);
}
fclose(fpt1);
}
Output
Input filename : Sample
Input data:
Name Age Height
Neeraj 21 172
Gaurav 20 175
Saurav 18 178
Data in input file:
Name Age Height
Neeraj 21 172.000000
Gaurav 20 175.000000
Saurav 18 178.000000
7.4.7 Random Access to Files
One advantage of data files over files on other devices (such as printers) is that a disk is a direct
access device. This means that a character can be written to or read from a disk file by specifying the
exact location from where this operation is to take place. This can be achieved with the help of the
functions fseek, ftell and rewind available in the I/O library.
The ftell function returns the current position of the file whose pointer is supplied as its function
argument. The function returns a long int value. It has the following form:
n = ftell(fptr);
where n would give the relative offset (in bytes) of the current position. It means that we have already
read or written n bytes in the file.
The rewind function takes a file pointer and resets the position again to the starting of the file. For
example,
rewind(fptr);
n = ftell(fptr);
112 Programming in C and Numerical Analysis

would assign 0 to n since the rewind ( ) resets the file position to the start of the file and the first byte
in the file is numbered starting from 0. This function helps in reading a file more than once without
having to close and open the file again and again. Whenever a file is opened for reading or writing, a
rewind( ) is done implicitly.
The fseek function is used to index a file. It is used to seek (or move to) a specific position in the
file. It takes the general form :
fseek(fptr, offset, position);
where fptr is a pointer to the file to be operated, offset is a long integer which specifies the positions
(bytes) to be moved from the location specified by position. The position can take one of the
following integer values :
0 start of file Remark
1 current position of the pointer
2 end of the file
The following table lists some sample pointer offset calls and their actions :
fseek call Action
fseek(fptr,0L,0); Go to start
fseek(fptr, 0L, 1); Stay at the current position
fseek(fptr, 0L, 2); Go to the end of file.
fseek(fptr, m, 0); Move to (m+1)th byte in the file.
fseek(fptr, m, 1); Go forward by m bytes from the current location.
fseek(fptr, m, 1); Go backward by m bytes from the current location.
fseek(fptr, m, 2); Go backward by m bytes from the end.
The user should avoid attempting to use fseek before the beginning of the file or after the end of
the file. The result of such attempts depends on the computer, but are not meaningful.
When the operation is successful, fseek returns a zero, otherwise in error condition, fseek returns
1. It is a good practice to check whether an error has occurred or not, before proceeding further.
Program to use show of fseek and ftell functions
#include <stdio.h>
void main ( )
{
long int n;
char filename[10], c;
FILE *fpt1;
printf(“\nInput file name:”);
scanf(“%s”, filename);
fpt1 = fopen(filename, “a+”);
printf(“File originally contained : \n”);
while((c = getc(fpt1))!=EOF)
putchar( c );
n = ftell(fpt1);
printf(“\Number of characters entered = %ld”, n);
Pointers and File in C 113

rewind(fpt1);
printf(“\nFile is now at position %ld”, ftell(fpt1));
fseek(fpt1, n, 0);
printf(“\nEnter data in file: \n”);
while((c = getchar ( )) != EOF)
putc(c, fpt1);
printf(“\nFile is now at position %ld”, ftell(fpt1));
printf(“\nThe number of characters appended is %ld”, ftell(fpt1)-n);
fseek(fpt1, n-ftell(fpt1), 2);
printf(“\nCharacters entered are: \n”);
Remarks while(( c = getc(fpt1)) != EOF)
putchar( c );
fclose(fpt1);
}

Output
Input file name: Sample
File originally contained:
Neeraj 21 172.000000Gaurav 20 175.000000Saurav 18 178.000000
Number of characters enterd = 60
File is now at position 0
Enter data in file:
File Handling is very easy to master.Always remember the basics. ^z
File is now at position 125
The number of characters appended is 65
Characters entered are:
File Handling is very easy to master. Always remember the basics.

Keywords : Pointers, pointer variable, call by reference, call by value, file name, gets, puts.
Summary : In this unit, we learn how pointers are used in C programming to make work easier which
saves memory. File in C programming is a very good tool to handle large data which can not be
handle by any other data type.
Remarks

CHAPTERVIII
SOLUTION OF ALGEBRAIC AND TRANSCENDENTAL EQUATIONS
8.0 STRUCTURE
8.1 Introduction
8.2 Objective
8.3 Bolzano or Bisection Method
8.4 Method of Regula Falsi
8.5 Order of Convergence of Regula Falsi
8.6 Secent Method
8.7 Newton Raphson Method
8.8 Newton-Raphson Iterative Formula for Finding the Inverse, Square Root
8.1 INTRODUCTION
Definition :
(a) Algebraic equation :- An equation of the form f(x) = 0 is called algebraic if f(x) is purely a

polynomial in x.
e.g. 3x5 + 5x2 + 7 = 0
(b) Transcendental equation :- An equation f(x) = 0 is called transcendental if it involves some
functions other than polynomial such as trigonometric algorithmic etc.
e.g. 1 + 2 cos x – 3x = 0
8.2 OBJECTIVE
At the end of this chapter students should be able to
 To know the analytical methods for finding the roots of non-linear equations
 Approximation methods for finding the roots algebraic and transcendental equations.
 Know the types of non-linear equations.
Method – Ist
8.3 BOLZANO OR BISECTION METHOD
If a function f : [a, b]   is continuous & such that f(a) f(b) < 0. Then by intermediate value
theorem J  (a, b) s.t.
f(x) = 0.
Basic idea of this method is to approximate the root of the equation f(x) = 0.
Assume without loss of generality that
f(a) > 0 & f(b) < 0.
Let Ist approximate to the root is

Now, there are two possibilities


(i) f(c) = 0, then c  (a, b) is a root of f(x) = 0.
(ii) f(c)  0, then either f(c) > 0 or f(c) < 0.
If f(c) > 0 then root lies between c & b.
If f(c) < 0 then root lies between a & c.
Again assume f(c) > 0
Then root lies between c & b.
Solution of Algebraic and Transcendental Equation 115

Remarks Again bisect the interval (c, b) & repeat the same process until the root is obtained of desired
accuracy.
e.g. 1) : Find a real root of the equation x 3 – x  11 = 0 by the Method of Bolzano, correct to the three
decimal places.
Solution : Here f(x) = x3 – x  11
Clearly f(2) = 23 – 2 – 11 = 5 < 0
f(3) = 33  3  11 = 13 > 0
Since f(2) & f(3) are of opposite sign and so root of f(x) = 0 lies in between 2 and 3.
So,

Ist Approximation to root =


f(2.5) = (2.5)3 – 2.5 – 11
= 15.625 – 2.5 – 11 = 15.625 – 13.500 = 2.125 > 0
So, f(2.5) > 0, f(2) < 0
So, root lies between 2 and 2.5.

2nd Approximation to the root =


f(2.25) = (2.25)3 – 2.25 – 11 = 1.8594 < 0
Thus, we have f(2.5) f(2.25) < 0
and so, root lies between 2.25 and 2.5

3rd Approximation to root =


f(2.375) = (2.375)3 – 2.375 – 11 = 0.0215 > 0
Thus, we have f(2.25) f(2.375) < 0
and so, root lies between 2.25 and 2.375

4th Approximation to root =


f(2.3125) = (2.3125)3 – 2.3125 – 11 = 0.9460 < 0
Thus, we have f(2.375) f(2.3125) < 0
and so root lies between 2.3125 and 2.375

5th Approximation to root =


and f(2.34375) = (2.34375)3 – 2.34375 – 11 =  0.4691 < 0
Thus, f(2.375) f(2.34375) < 0
So, root lies between 2.34375 and 2.375

6th Approximation to root =


f(2.3594) = (2.3594)3 – 2.3594 – 11 =  0.2252 < 0
Thus, f(2.375) f(2.3594) < 0
So, root lies between 2.3594 and 2.375

 7th Approximation to root =


f(2.3672) = (2.3672)3 – 2.3672 – 11 =  0.1023 < 0
Thus, f(2.3672) f(2.375) < 0
and so, root lies between 2.3672 and 2.375
116 Programming in C and Numerical Analysis

Remarks
th
8 Approximation to root =
f(1.3711) = (1.3711)3 – 1.3711 – 11 =  0.0405 < 0
Thus, f(2.3711) f(2.375) < 0, so, root lies between 2.3711 and 2.375.

 9th Approximation to root =


f(2.3731) = (2.3731)3 – 2.3731 – 11 =  0.0087 < 0
Thus, f(2.3731) f(2.375) < 0
So, root lies between 2.3731 and 2.375

10th Approximation to root =


Hence the required root correct to three decimal places of decimal = 2.3741  2.374
e.g. 2) Here given equation x3 – x – 1 = 0
Solution : Let f(x) = x3 – x – 1
Clearly f(1) =  1, f(2) = 5
 f(1)(2) < 0
Therefore, root lies between 1 and 2.

1st Approximation to root =


f(1.5) = (1.5)3 – 1.5 – 1 = 0.875
Thus, we have f(1) f(1.5) < 0
 root lies between 1 and 1.5.

2nd Approximation to root =


f(1.25) = (1.25)3 – 1.25 – 1   0.2969
 f(1.5) f(1.25) < 0
 root lies between 1.25 and 1.5

 3rd Approximation to root =


f(1.375) = (1.375)3 – 1.375 – 1 = 0.2246
Thus, f(1.25) f(1.375) < 0
 root lies between 1.25 and 1.375

4th Approximation to root =


f(1.3125) =  0.0515 < 0
Thus, f(1.3125) f(1.375) < 0
So, root lies between 1.375 and 1.3125

5th Approximation to root =


f(1.3438) = (1.3438)3 – 1.3438 – 1 = 0.0828 > 0
Thus, we have f(1.3125) f(1.3438) < 0
 Root lies between 1.3125 and 1.3438

6th Approximation to the root =


f(1.3282) = 0.0148 > 0
Solution of Algebraic and Transcendental Equation 117

Thus, f(1.3125) f(1.3282) < 0

Remarks  Root lies between 1.3125 and 1.3282

7th Approximation to root =


f(1.3204) = (1.3204)3 – 1.3204 – 1 =  0.0183 < 0
Thus, f(1.3282) f(1.3204) < 0
 Root lies between 1.3204 and 1.3282

8th Approximation to root =


 Required root correct to three decimal places = 1.324
8.4 METHOD OF REGULA FALSI :
Aim : To find the real root of the equation f(x) = 0.
Explanation of Method : Like bisection method, here also we choose x 0 and x1 close, so that f(x0)
f(x1) < 0.
So, we get the interval (x0, x1). A (x0, f(x0))
Now, basic idea of the this method is
to approximate the graph y = f(x) of .
c.y= f(x)
f(x) by a straight line joining (x0, f(x0)) and (x1, f(x1)).
Since root of f(x) = 0
x2
. ..
lies between x0 and x1
So,    
st. x0 <  < x1
st. f(x) = 0
So, (, 0) is the point where graph of f(x) crosses x-axis. (x1, f(x1))
B
Now, the equation of straight line joining A(x0, f(x0)) and B(x1, f(x1)) is

(1)
So, the 1st approximation to the root  of f(x) = 0 is given by putting y = 0 in equation (1), so we get

Now, we will check whether


 f(x2) f(x0) < 0 or f(x2) f(x1) < 0
Then in the same way we can find the 2nd approximation.
In particular we define it (i + 1)th approximation by

Definition : Order of convergence of an Iterative Method :


Let  be the root of f(x) = 0 and ei be the small quantity by which xi is differ from . Then
xi   = ei and xe+I   = ei+1 etc.
The order of convergence of an iterative process is p, if p is the smallest number such that

where K  
8.5 ORDER OF CONVERGENCE OF REGULA FALSI
118 Programming in C and Numerical Analysis

Let  be the root of f(x) = 0. ei be the small quantity by which xi differ from .
Then
Remarks

By Regula Falsi Method

Using equation (*), we get

Which on solving, gives

Now, using f() = 0, we get

Let p be the order of convergence then by definition  K   st.


Solution of Algebraic and Transcendental Equation 119

Choose K and K st.


Remarks

Taking +ve signs, we get

Thus, order of convergence of Regula Falsi Method = 1.618


8.6 SECENT METHOD :
Like Regula Falsi, this method is also, based on approximation the graph of f(x) by straight
line in the nbd of root. But in this method, in each iteration it is not necessary that the interval must
contain the root.
Taking x0, x1 as initial limits of interval. Then the equation fo line joining the points A(x 0, f(x0))
and B(x1, f(x1)) is

Now, the Abscissa of the point where it crosses the x-axis is given by

Which is an approximation to the root of the equation f(x) = 0.


Then the general formula for successive approximation is given by

Remark : If f(xi+1) = f(xi) then this method fails and it does not converge.
Question 1 : Find the root of the equation x4 – x – 10 = 0 using Secent Method.
Solution : Let f(x) = x4 – x – 10
Taking x0 = 1, x1 = 2, we have
f(x0) = 14 – 1 – 10 =  10
f(x1) = 24 – 2 – 10 = 4
Iteration Ist
120 Programming in C and Numerical Analysis

 x2 = 1.7143
f(x2) = f(1.7143) =  3.0776 Remarks
Iteration 2nd

 x3 = 1.8385
f(x3) = f(1.8385) =  0.4135
Iteration 3rd

 x4 = 1.8578
f(x4) = 0.05451
Iteration 4th

 x5 = 1.8556
f(x5) = 0.00038
Iteration 5th

 x6 = 1.8556
Hence, the required root of given equation = 1.8556
Question 2 : Find the real root of the equation x3 – 4x – 9 = 0 using Regula Falsi Method.
Solution : Here given equation is
x3 – 4x – 9 = 0
Let f(x) = x3 – 4x – 9
Clearly, f(2) =  p < 0, f(3) = 6 > 0
So, f(2) f(3) < 0
 Root lies between 2 and 3
1st Approximation x(1), is given by

where x0 = 2, x1 = 3
f(x0) =  9, f(x1) = 6
Solution of Algebraic and Transcendental Equation 121

x(1) = 2.6
Now, f(2.6) = (2.6)3  42.6  9
= 17.576  10.4  9
= 17.576  19.400 =  1.824 < 0
Now, since f(2.6 f(3) < 0
 Root lies between 2.6 and 3
Remarks 2nd Approximation is given by

where x0 = 2.6, x1 = 3
f(x0) =  1.824, f(x1) = 6

x(2) = 2.6932
f(x ) = f(2.6932) =  0.2381 < 0
(2)

So, root lies between 2.6932 and 3


3rd Approximation is given by

where x0 = 2.6932, x1 = 3
f(x0) =  0.2381, f(x1) = 6

x(3) = 2.7048
Hence the required root is 2.705.
8.7 NEWTON RAPHSON METHOD
Explaination of Method : Let x0 be an approximate value of root of the equation f(x) = 0. Let x 0 + h
be the exact value of the corresponding root; where h is the small quantity. Then
f(x0 + h) = 0
using Taylor’s Series, we get

Neglecting the higher powers of h, we get


f(x0) + h1 f(x0) = 0
122 Programming in C and Numerical Analysis

Now, x0 + h1 is Mere Close to the root than x0


say x0 + h1 = x1

Apply the same procedure with x1 we get,

Continuing like this, we get at the (n + 1)th stage


Remarks

Provided f(xn)  0.
This is called Newton-Raphson Formula.
. x0
Geometrically
In this method, if x0 is the initial approximate
value of root, then we take the tangent at
(x0, f(x0)) and see the point, where this tangent
Crosses the x-axis. The point where it crosses the x-axis we call . that
x1
point at (x1, 0). Clearly this point satisfies

we continuing like this with x1 and so on, we get

Order of Convergence of Neewton Raphson Method


Let  be the root of the equation f(x) = 0 and ei is the smallest quantity by which xi differs from .
Then xi   = ei and xi+1   = ei+1 (*)
Now, by Newton – Raphson Formula we have,

Using (*) we get,


Solution of Algebraic and Transcendental Equation 123

Remarks

 Order of Convergence of Newton-Raphson Method = 2.


Question 1 : Find the real root of x 4 – x – 10 = 10 by NewtonRaphson Method which is near 2,
correct to three decimal places.
Solution : Let f(x) = x4 – x – 10, f(x) = 4x3 – 1
x0 = 2 (given)
Also f(1) =  10, f(2) = 4
 Root lie between 1 and 2, is close to 2.
Now, by Newton-Raphson Method
Ist Approximation is

 x1 = 1.871
2nd Approximation is

x2 = 1.856 (where x1 = 1.871)


3rd Approximation is
124 Programming in C and Numerical Analysis

 x3 = 1.856 (where x2 = 1.856)


Hence, 1.856 is the required root correct to three decimal places.
8.8 NEWTON-RAPHSON ITERATIVE FORMULA FOR FINDING THE INVERSE, SQUARE ROOT ETC.
(1) Inverse

The reciprocal or inverse of number N  0 is the root if the equation = N. This can be solved
by Newton-Raphson Method as follows
Remarks
Let

By Newton-Raphson Method, we have

After solving, we get


xn+1 = xn (2 Nxn)
(2) Square Root
Let N > 0 by any real number (fixed). Then square root of N is the root of the equation x 2 – N = 0
Here
f(x) = x2 – N
f(x) = 2x
By Newton-Raphson Method, we have

(3) Inverse Square Root

Inverse square root of N > 0, a real number is a root of the equation .

Here,

By Newton-Raphson Method, we have


Solution of Algebraic and Transcendental Equation 125

Finally we can find the Iterative formula for pth root and inverse pth root.
Exercise 8.1
Remarks
1 : Find the cube root of 3, correct to three decimal by Newton-Raphson Method.
Ans. 1.442
2 : Find the real root of the following equation using Newton-Raphson Method, correct to three
decimal places :
(a) x3 – 5x + 3 = 0 Ans. 1.834
(b) x4 – x – 9 = 0 Ans.1.813
3 : Find the real root of above equations in (a) and (b) using Regula Falsi – Method, correct to three
decimal places.
(a) x3 – 9x + 1 = 0 Ans. 0.111
3
(b) x – 5x – 7 = 0 Ans. 2.748

4 : Find (i) (ii) (iii) using Newton-Raphson Method.


Ans. (i) 5.916 (ii) 3.873 (iii) 4.472

5 : Find the value of , using Newton-Raphson Method. Ans. 0.032


6: Find the real +ve root of x3 x  11 = 0 correct to three decimal places by using bisection method.
Ans. 2.374

Keywords : Bisection method, Regula falsi method, Newton-Raphson method, order of Convergence.
Summary
In this chapter, the techniques for solution of non-linear equations have been discussed with
examples and their order of convergence so that solution of various non-linear equations can be
determine easily.
CHAPTER – IX Remarks

INTERPOLATION WITH EQUAL INTERVALS


9.0 STRUCTURE
9.1 Introduction
9.2 Objective
9.3 Newton Forward Formula for Interpolation
9.4 Newton Backward Formula for Interpolation
9.5 Central Difference Interpolation Formula
9.1 INTRODUCTION :
“Interoplation is the art of reading between the lines of a table”.
Theile
Finite differences play an important role in numerical techniques, where tabulated values of the
functions are available. For instance, consider a function y = f(x). As x takes values x 0, x1, x2, …, xn,
let the corresponding values of y be y 0, y1, y2, …, yn. That is for a given table of values (x k, yk), k = 0,
1, 2, 3, …, n; the process of estimating the value for y, for any intermediate value of x, is called
interpolation. However, the method of computing the value of y, for a given values of x, lying outside
the table of values of x is known as extrapolation. It may be noted that if the function f(x) is known,
the value of y corresponding to any x can be readily computed to the desired accuracy. But, in
practice, it may be difficult or sometimes impossible to know the function y = f = f(x) in its exact
form.
We will discuss a practical example; let us consider the computation of trajectory of a rocket
flight, where we solve the Euler’s dynamical equations of motion t compute its position and velocity
vectors at specified times during the flight. Under the same conditions, suppose, we require the
position and velocity vector, at some other intermediate times; we need not compute the trajectory
again by solving the dynamical equations. Instead, we can use the best known interpolation technique
to get the desired values.
In numerical methods we come across functions defined by set of tabulated points (x 0, y0), (x1, y1),
(x2, y2), …, (xn, yn), though the explicit nature of the function y = f(x) is not known. In this case we
consider a general form of the polynomial.
y = (x) = a0 + a1x + a2 x2 + …. + an xn, which agree at the above set of tabulated points. The
function (x) may not exactly define the function y = f(x) as there may be a set of points other than
(xi, yi), i = 0, 1, 2, …,n, that satisfy the relation y = f(x) but may not satisfy the general form. In this
case we treat the general form of the polynomial as an approximation to y = f(x). The polynomial
(x) is known as interpolation polynomial.
9.2 OBJECTIVE
At the end of this unit, students should be able to
1. Apply forward interpolation with equal difference.
2. Apply backward interpolation with equal difference.
3. Apply central interpolation with equal difference.
9.3 NEWTON FORWARD FORMULA FOR INTERPOLATION
Ley y = f(x) be a function of x which assumes the values f(a), f(a + h), f(a + 2h), …, f(a + nh) for
n + 1 equidistant values a, a + h, a + 2h, …., a + nh of x. Let us assume that f(x) is a polynomial in x
of degree n and may be written as
f(x) = G0 + G1(x  a) + G2(x  a)(x  ) + G3(x  a) (x  )(x  )

+… + Gn(x  a) (x  )…(x  ) (1)


where G0, G1, …, Gn are constans to be determined.
Now, put x = a, a + h, a + 2h, …., a + nh in (1), we get
Interpolation with Equal Intervals 127

Remarks For x = a, f(a) = G0 (2)


For x = x + h, f(a + h) = G0 + G1.h
 G1h = f(a + h)  G0
= f(a + h) – f(a) = f(a) [From (2)]

 (3)
For x = a + 2h, f(a + 2h) = G0 + G1.2h + G2(2h).h
 G2.2h2 = f(a + 2h)  G0  G1.2h

= f(a + 2h)  f(a)  .2h [Using (2) and (3)]


= f(a + 2h)  f(a)  2{f(a + h)  f(a)}
= f(a + 2h)  2f(a + h) + f(a)
= {f(a + 2h)  f(a + h)}  {f(a + h)  f(a)
= f(a + h)  f(a) = 2f(a).

 G2 =

Similarly, we have
………………………
………………………

Substituting the values of G0, G1, G2, …., Gn in (1), we get

f(x) = f(a) + (x  a) + (x  a) (x  ).

+ (x  a) (x  ) (x  ) + …….

….+ (x  a) (x  )…(x  ) (4)


which is Newton Forward Formula for Interpolation.
This formula is used mainly for interpolating the values of f(x) near the beginning (x > a) of the
set 0f tabulated values.

Put u = i.e., x = a + uh,


where x is the value of the variable at which the value of function is to be interpolated
 x  a = uh
Also (x  ) = (u  1)h,
x = (u – 2)h,
…………………
…………………
128 Programming in C and Numerical Analysis

Remarks
x = (u  )h,
Now putting all these values in (4), we have

f(a + uh) = f(a) + (uh) + (uh)(u  1). …………

+ (uh) (u  1) h(u  2) h. + …..

….+(uh) (u  1) h…(u  )h

= f(a) + uf(a) + 3f(a) +…

….+
The above result can be written as

(5)
where u = u.(u  1).(u  2)….(u  r + 1) is factorial polynomial order r.
(r)

This is the form in which Newton Forward Formula for Interpolation is usually written.
Example 1 : Evaluate f(15), given the following table of values :

x 10 20 30 40 50
y = f(x) 46 66 81 93 101

Solution : The value x = 15 is near to the beginning of the table. We use Newton’s forward difference
interpolation formula.

x y y 2y 3y 4y


10 46
20
20 66 5
15 2
30 81 3 3
12 1
40 93 4
8
50 101
Using Newton forward difference formula

where x = x0 + uh.
Here h = 10, x0 = 10, y0 = 46, y0 = 20, 2y0 = 5, 3y0 = 2, 4y0 = 3.

Therefore, .
Interpolation with Equal Intervals 129

y(15) = 46 + (0.5)(20) +
Remarks
= 56.8672
Example 2 : Find the missing term in the following table

x 0 1 2 3 4 5
y 1 2 4 8  32
Explain why does it differ from 16.
Solution : There are 5 tabulated values, that is, (0, 1), (1, 2), (2, 4), (3, 8) and (5, 32) are given,
therefore its 5th forward difference must be zero.
By constructing difference table
x y y  2y 3y 4y 5y
0 1
1
1 2
2
2 4 1
4 1
3 8 2 a15
a8 a14 815a
4 a(say) a12 664a
32a 523a
5 32 402a
Now we put 5y = 0, we get 81 – 5a = 0.

This implies that a = at x = 4


Observation of the given data is of the form 2x. But the formula that we have used holds good
when f(x) is a polynomial of degree 4.
Example 3 : Find the cubic polynomial which takes the following values y(0) = 1, y(1) = 0, y(2) = 1
and y(3) = 10. Hence or otherwise, obtain y(0.5).
Solution : It gives that
x0 = 0, x1 = 1, x2 = 2, x3 = 3
and y0 = 1, y1 = 0, y2 = 1, y3 = 10
We form the difference table

x y  2 3
x0 = 0 y0 = 1
y0 = 1
x1 =1 y1 = 0 2y0 = 2
y1 = 1 3y0 = 6
x2 =2 y2 =1  y1 = 8
2

y2 = 9
x3 =3 y3 = 10
From the above table we have,
x0 = 0, y0 = 1, y0 = 1, 2y0 = 2, 3y0 = 6
130 Programming in C and Numerical Analysis

Using Newton forward difference formula, we get Remarks

where x = x0 + uh
Here h = 1, x0 = 0, therefore, u = x

= 1 – x + (x2 – x) + (x3 – 3x2 + 2x)


y(x) = x3 – 2x2 + 1
which is the polynomial from which we obtained the above tabular values.
To find y(0.5)
Here x0 + uh = x = 0.5
u = 0.5 since x0 = 0 and h = 1

= 0.625 (Ans.)
which is the same value as that obtained by substituting x = 0.5 in the cubic polynomial.
Example 4 : From the following table, estimate the number of students who obtained marks between
40 and 45.
Marks 30 – 40 40 – 50 50 – 60 60 – 70 70 – 80
No. of Students 31 42 51 35 31

Solution : First we prepare the cumulative frequency table, as follows,


Marks less than (x) 40 50 60 70 80
No. of Students y 31 73 124 159 190

Now the difference table is


x y  2 3 4
40 31
42
50 73 9
51 25
60 124 16 37
35 12
70 159 4
31
80 190

We shall find the number of students with marks less than 45.

Here x = 45, a = 40, h = 10,


As we know that Newton forward Interpolation formula is
Interpolation with Equal Intervals 131

Remarks

= 31 + 21  1.125  1.5625  1.4453 = 47.87 48


The number of students with marks less than 45 is 48. But the number of students with marks less
than 40 is 31.
Hence the number of students getting marks between 40 and 45 is 48 – 31 = 17.
9.4 NEWTON BACKWARD FORMULA FOR INTERPOLATION
Let y = f(x) be a function of x which assumes the values f(a + nh), f(a + h)… ..,f(a) for x = a
+ nh, a + h, a + h, a i.e. we are given n + 1 equidistant values of the function.
Then to n + 1 observations, we can fit a polynomial of nth degree.
Let us assume that f(x) is a polynomial in x of degree n and may be written as

f(x) = G0 + G1(x ) + G2(x (x ) + …..

…..+ Gn(x )(x )…..(x ), (1)


where G0, G1, G2,…., Gn are constants to be determined.
Now, put x = a + nh, a + h, a + h,….., a + h in (1), we get
For x = a + nh :
f(a + nh) = G0
For x = a + h:
f(a + h) = G0 + G1(h)

For x = a + :
f(a + h) = G0 + G1(2h) + G2(2h)(h)
2
2h G2 = f(a + )  G0 + 2h.G1

= f(a + )  f(a + nh) + 2h.


= f(a + )  f(a + nh) + 2[f(a + nh)  f(a + h)]
= [f(a + nh)  f(a + h)]  [f(a + h)  f(a +
= ∇f(a + nh)  ∇f(a +
)]

= ∇2f(a + nh)
h)

Similarly,
………………
………………
132 Programming in C and Numerical Analysis

Substituting the values of G0, G1, G2, …., Gn in (1), we get


Remarks

f(x) = f(a + nh) + + (x  )(x +..

…..+ (x  )(x (2)


which is Newton Backward formula for interpolation.
This formula is useful for a interpolating the value of f(x) near the end of the set of tabulated
values.

Put i.e., x = a + nh + uh,


where x is the value of the variable at which the value of function is to be interpolated.
x = uh

Also, x = (u + 1)h
………………………..
………………………..
Putting all these values in (2), we have

….. (3)
This is the form in which Newton Backward formula for interpolation is usually written.
Example 1 : The sales in a particular department store for five years are given in the following table :
Year 1974 1976 1978 1980 1982
Sales (in lkh.) 40 43 48 52 57
Estimate the sales for the year 1979.
Solution : We construct the backward difference table is
x y ∇ ∇2 ∇3 ∇4
1974 40
3
1976 43 2
5 3
1978 48 1 5
4 2
1980 52 1
5
1982 57

From the table, we find, with xn = 1982, yn = 57, ∇yn = 5, ∇2yn = 1, ∇3yn = 2, ∇4yn = 5.
We shall find the Estimate sales for the year 1979.
Interpolation with Equal Intervals 133

By the Newton’s interpolation formula,

.
Remarks Example 2 : Using Newton’s backward interpolation formula, find the interpolating polynomial that
approximates the function given by the following table :
x 0 1 2 3
f(x) 1 3 7 13

Hence find f(2.5)


Solution : For the given data, the backward difference table is as shown below :
x y ∇ ∇2 ∇3
x0 = 0 1
2
x1 = 1 3 2
4 0
x2 = 2 7 2
6
x3 = 3 13

From the table, we find, with xn = x3 = 3, yn = 13, ∇yn = 6, ∇2yn = 2, ∇3yn = 0.


For x = xn + uh, we have

and the Newton’s backward interpolation formula gives

y(x) = 13 + 6(x  3) + (x – 3) (x – 3 + 1) + 0
= x2 + x + 1.
Thus, y(x) = x2 + x + 1 is the interpolating polynomial that approximates the given function.
Hence, f(2.5) y(2.5) = (2.5)2 + 2.5 + 1 = 9.75
Example 3 : From the following table, find y when x = 2.4 by Newton’s interpolation formula
x 1.7 1.8 1.9 2.0 2.1 2.2 2.3
y = ex 5.474 6.50 6.686 7.389 8.166 9.025 9.974
Solution : The difference table is as under
x y = ex ∇ ∇2 ∇3 ∇4 ∇5 ∇6
1.7 5.474
0.576
1.8 6.050 0.06
0.636 0.007
1.9 6.686 0.067 0.00
0.703 0.007 0.001
2.0 7.389 0.074 0.001 0.002
0.777 0.008 0.001
2.1 8.166 0.082
134 Programming in C and Numerical Analysis

0.00
0.859 0.008
2.2 9.025 0.09
0.949
2.3 9.974

As x = 2.4 lies out side the table, so we cann’t interpolate. But if we assume that the trend outside
the table is same as inside the table, then we determine y when x = 2.4. Remarks

Here, (we take a = 2.3)


From Newton Backward’s difference formula, we get

= 9.974 + 0.949 + 0.09 + 0.008 + 0.00 – 0.001 – 0.002 = 11.016.

Example 4 : Find the value of an annuity at , given the following table :


Rate percent : 4 5 6

Annuity value : 17.29203 16.28889 15.37245 14.53375 13.76483


Solution : The difference table is as under
x 105y 105∇y 105∇2y 105∇3y 105∇4y
4 1729203
100314
1628889 8670

91644 896
5 1537245 7774 100
83870 796
1453375 6978
76892
1376483
6

Here the value to be interpolated lies near the end of the tabulated values. Hence we may use
Newton’s backward formula for interpolation.

Here a + nh = 6, h = and x=
Interpolation with Equal Intervals 135

Now, by Newton’s formula for backward interpolation, we have

Remarks

= 1376483 + 96115 + 1090  31 + 1.7 = 1473658.7


EXERCISE  9.1
Question 1 :Construct Newton’s forward interpolation polynomial for the following data :
x: 4 6 8 10
f(x) : 1 3 8 16

Question 2 :From the following table, find the number of students who obtained marks less than 45.

Marks No. of Students


30 – 40 31
40 – 50 42
50 – 60 51
60 – 70 35
70 – 80 31

Question 3 :The population of a town is as follows :

Year : 1961 1971 1981 1991 2001 2011


Population (in lacs) : 20 24 29 36 46 51

Estimate the increase in population during the period 1995 to 2001.


Question 4 : The Population of a country is as follows :

Year : 1971 1981 1991 2001 2011


Population (in crores) : 46 66 81 93 101

Estimate the population for the year 2005.


136 Programming in C and Numerical Analysis

Question 5 : The following are the number of deaths in four successive ten years age groups. Find the
number of deaths at 45 – 50 and 50 – 55

Age Group : 20 – 35 35 – 45 45 – 55 55 – 65
Deaths : 13229 18139 24225 31496

ANSWERS
1. 1.625 2. 48 3. 6.2104 lacs
4. 96.8368 crores 5. 11278, 12947

9.5 CENTRAL DIFFERENCE INTERPOLATION FORMULA Remarks


We have discussed Newton’s forward and backward interpolation formulae. Newton’s forward
formula is applicable for interpolation near the beginning of the tabulated values whereas Newton’s
backward formula is applicable for interpolation near the end of the tabulated values. If the value of
the function is required near the middle of the table, then Newton’s forward and backward
interpolation formulae are not suitable. In this case central difference interpolation formulae are more
suitable.
The most commonly used central difference interpolation formulae are :
1. Gauss Forward Interpolation Formula
2. Gauss Backward Interpolation Formula
3. Sterling Formula
4. Bessel’s Formula
1. Gauss Forward Interpolation Formula
Newton’s formula for forward interpolation can be written as
yx = y0 + u(1)y0+ u(2)2y0+ u(3)3y0+ u(4)4y0 +…… (1)

where
which is also known as Newton’s advancing formula.
Now, in equation (1), except the first two terms on R.H.S., the subscript of y in each term is
diminished by 1, using the formula
n+1y-1 = ny0  ny-1
ny0 = ny-1 + n+1y-1
Putting n = 2, 3, 4, …. in result (2), we have
2y0 = 2y-1 + 3y-1
3y0 = 3y-1 + 4y-1
4y0 = 4y-1 + 5y-1
…………………
…………………
Using these results in equation (1), we have
yx = y0 + u(1)y0 + u(2)(2y-1+3y-1) + u(3)(3y-1+4y-1) + u(4)(4y-1+5y-1) +…
= y0 + u(1)y0 + u(2)2y-1+ (u(2) + u(3))3y-1 + (u(3) + u(4))4y-1 +…
But u(i-1) + u(i) = (u + 1)(i), where i = 3, 4…. [ nCr-1 + nCr = n+1Cr]
yx = y0 + u(1)y0 + u(2) y-1+ (u+1)(3) y-1 + (u + 1)(4)4y-1 +…
2 3

Now, reducing the subscript of y of fifth term and onwards by 1, we have


yx = y0 + u(1)y0 + u(2)2y-1+ (u+1)(3)3y-1 + (u + 1)(4) (4y-2 +5y-2)+…
[ ny-1 =ny-2 + n+1y-2, 4y-1 = 4y-2 + 5y-2 ]
Interpolation with Equal Intervals 137

yx = y0 + u(1)y0 + u(2)2y-1+ (u+1)(3)3y-1 + (u + 1)(4)4y-2 + ….


This is called the Gauss Forward Interpolation Formula.

Remark : Gauss Forward formula is useful when u lies between 0 and .


Example 1 : Apply Gauss forward formula to obtain f(x) at x = 3.5 from the table
x 2 3 4 5
f(x) 3.818 2.423 1.027 2.794

Solution : Here x0 = 3, x = 3.5, h = 1,

Remarks The difference table for this is


x u y ∇y ∇2y ∇3y
2 1 3.818
1.395
0 2.423 2.055
3
3.45 3.738
4 1 1.027 1.683
1.767
5 2 2.794
So by Gauss Forward formula, we have

= 2.243 + (0.5)(3.45) +
= 2.243  1725 + 0.2569  0.2336
= 0.72131
Example 2 : Find the value of y at x = 0 using Gauss Forward formula from the table below

x 21 25 29 33 37
y 18.4708 17.8144 17.1070 16.3432 15.5154

Solution : The difference table is

x u y ∇y ∇2y ∇3y ∇4y


21 2 18.4708
0.6564
1 17.8144 0.0510
25
0.7074 0.0054
29 0 17.1070 0.0564 0.0022
138 Programming in C and Numerical Analysis

0.7638 0.0076
33 1 16.3432 0.0640
0.8278
37 2 15.5154

Here x0 = 29, x = 30, h = 4

So, by Gauss Forward formula, we have

Remarks

= 17.1070 + (0.25) (0.7638) +

= 17.1070  0.19095 – 0.0052875 + 0.0003 – 0.00004


2. Gauss Backward Interpolation Formula
We know that Newton’s advancing formula is
yx = y0 + u(1)y0+ u(2)2y0+ u(3)3y0+ u(4)4y0 +…… (1)
Here, except the first term on R.H.S., the subscript of y in each term is reduced by 1, using the
formula
ny0 = ny-1 + n+1y-1 (2)
Putting n = 1, 2, 3, 4,… in (2), we have
y0 = y-1 + 2y-1
2y0 = 2y-1 + 3y-1
3y0 = 3y-1 + 4y-1
4y0 = 4y-1 + 5y-1
…………………
…………………
Using these results in equation (1), we have
yx = y0 + u(1)(y-1 +2y-1) u(2)(2y-1+3y-1) + u(3)(3y-1+4y-1) + u(4)(4y-1+5y-1) +…
= y0 + u(1)y-1 + (u(1) + u(2))2y-1+ (u(2) + u(3))3y-1 + (u(3) + u(4))4y-1 +…
= y0 + u(1)y-1 + (u + 1)(2) 2y-1+ (u + 1)(3) 3y-1+(u + 1)(4) 4y-1+ …… (3)
[ u(i-1) = + u(i) = (u + 1)(i)]
Again, suffix of y in each term of (3) except first three is reduced by 1, by using the formula
ny-1 = ny-2 + n+1y-2
Putting n = 3, 4, …., we have
3y-1 = 3y-2 + 4y-2
4y-1 = 4y-2 + 5y-2
…………………
…………………
Using these results in equation (3), we have
yx = y0 + u(1)y-1 + (u + 1)(2) 2y-1+ (u + 1)(3) [3y-2 + 4y-2]
Interpolation with Equal Intervals 139

+(u + 1)(4) [4y-2 + 5y-2] ……


= y0 + u(1)y-1 + (u + 1)(2) 2y-1+ (u + 1)(3) 3y-2 + [(u + 1)(3)(u + 1)(4)] 4y-2 +....
 yx = y0 + u(1)y-1 + (u + 1)(2) 2y-1+ (u + 1)(3) 3y-2 +(u + 2)(4)4y-2 +....
which is the Gauss Backward Interpolation Formula

Remark : Gauss Backward formula is useful when u lies between and 0.


Example 1 : Given that

Show by Gauss backward formula that

Remarks Solution : We know that Gauss’s backward formula is useful when x lies between 1/2 and 0. Here
interval of differencing is 10 and we are to calculate the value of y at x = 12516. Therefore, shifting
the origin at 12520 and h = 10 as the unit i.e., we define

Now the value of y required for

∇y ∇2y ∇3y
The difference table is as under
u y
2 111.803399
0.044712
1 111.848111 0.000017
0.044695 0.000001
0 111.892806 0.000018
0.044677
1 111.937483
We know that the Gauss backward formula is

Substituting u = 0.4 and putting the values of y0 and its differences, we get

= 111.892806 – 0.017878 + 0.000002 = 111.874930.


3. Sterling’s Formula
Let y = f(x) be a given function. Let …., x -2, x-1, x0, x1, x2,…. are given set of observations with
common difference h and …., y-2, y-1, y0, y1, y2,….are their corresponding values. Then
140 Programming in C and Numerical Analysis

where
Proof : Sterling’s formula is obtained from the average of Gauss forward and Gauss backward
formula
As we know from Gauss forward formula

(1)
Also, form Gauss Backward formula,

Remarks

(2)

So, Sterling’s formula = (Gauss Forward formula + Gauss Backward formula)

Note : Sterling’s formula is useful when u lies in between  to . But it gives best estimate when

u lies in to .
Example 1 : Use Sterling’s formula to find the value of , given that :

Solution : Take the origin at 22 and h = 1 as unit.

Let us take .

We are to calculate value of y for = 0.2.


The difference table is as under
u y y 2y  3y 4y
2 4.472
0.111
1 4.583 0.004
0.107 0.003
Interpolation with Equal Intervals 141

0 4.690 0.001 0.005


0.106 0.002
1 4.796 0.003
0.103
2 4.899

We know that the Sterling’s formula is

 y0.2 = 4.690 + 0.2  (0.107 + 0.106) + 

Remarks

= 4.690 + 0.0213  0.00002 = 4.71128

i.e., y22.2 = 4.71128.

4. Bessel’s Formula

Let y = f(x) be a given function. Let ….,x-2, x-1, x0, x1, x2,… are given set of observations with

common difference h and …,y-2, y-1, y0, y1, y2,… are their corresponding values. Then

Solution : We know by Gauss forward formula that

(1)
Also, from forward difference table, we have
y1 – y0 = y0
Implies, y0 = y1  y0
Also, 2y-1 = 2y0  3y-1
Similarly, 2y-2 = 4y-1  3y-2 etc.,
So, equation (1) can be written as
142 Programming in C and Numerical Analysis

Now, using the above results, we obtain

Remarks

Example 1 : Apply Bessel’s formula to obtain y25, given


y20 = 2854, y24 = 3162, y28 = 3544, y32 = 3992.
Solution : Take 24 as the origin and 4 as the unit. We are to calculate yu for value of

The difference table is as under


u yu yu 2yu 3yu
1 2854
308
0 3162 74
382 8
1 3544 66
448
2 3992

Using Bessel’s formula,


Interpolation with Equal Intervals 143

= 3353 – 95.5 – 6.5625 – 0.0625 = 3250.875

EXERCISE  9.2

Question 1 : Find the value of f(26) given that

f(20) = 3010, f(25) = 3979, f(30) = 4771, f(35) = 5441, f(40) = 6021.

Apply Gauss backward formula.

Question 2 : Find the population of the town in 1986, given that

Year : 1971 1981 1991 2001 2011

Population (in millions) : 15 20 27 39 52

Remarks Question 3 : Given

 0 5 10 15 20 25 30

tan  0 0.0875 0.1763 0.2679 0.3640 0.4663 0.5774

Using Sterling’s formula, show that tan 16 = 0.2867.

Question 4 : Apply Bessel’s formula for finding the value of y for x = 3.75, given that

x: 2.5 3.0 3.5 4.0 4.5 5.0

y: 24.145 22.043 20.225 18.644 17.262 16.047

ANSWERS
144 Programming in C and Numerical Analysis

1. 4149.8 2. 22.898 4. 19.407

Keywords : Equal intervals, forward difference, backward difference, central difference.

Summary : In this unit we have discussed various types of interpolation with equal intervals. They

may be forward, backward and central, using these methods we estimate function values at any point.
Remarks

CHAPTER – X
INTERPOLATION WITH UNEQUAL INTERVALS
10.0 STRUCTURE
10.1 Introduction
10.2 Objective
10.3 Lagrange’s Interpolation Formula
10.4 Divided Differences
10.5 Newtons’s Divided Differences Formula
10.6 Hermite Interpolation Formula
10.1 INTRODUCTION
As we discuss Newton’s interpolation formula in the previous chapter can be used only when the
values of independent variable are equally spaced and differences of y are small. Now we discuss the
method where values of independent variable are not given at equidistant.
10.2 OBJECTIVE
At the end of this unit students should be able to
1. The concept of finite difference with unequal intervals.
2. Application of interpolation formula
10.3 LAGRANGE’S INTERPOLATION FORMULA
If y = f(x) be a function which takes the values (x0, y0), (x1, y1),…..,(xn, yn). Since there are (n + 1)
pairs of values of x and y, then we can find f(x) by a polynomial on x of degree n as

y = f(x) =

……………………………………………………….

Proof : Let f(x) be the nth degree polynomial of x and x0, x1, x2, x3, …., xn be the values of arguments
not equally spaced and corresponding entries be y0, y1, y2, y3, …., yn.
Now consider the function f(x) as
f(x) = A0(x – x1)(x – x2)….(x – xn) + A1(x – x0)(x – x2)…(x – xn)
+ A2(x – x0)(x – x1)…(x – xn) + …+ An(x – x0)(x – x1)…(x-xn-1) (1)
where A0, A1, A2, …, An are the constants to be determined.
Putting x = x0 in (1) we have
y0 = A0(x0 – x1)(x0 – x2) …(x0 – xn)

 A0 =
Now, putting x = x1 in (1), we have
y1 = A1(x1 – x0)(x1 – x2)….(x1 – xn)
146 Programming in C and Numerical Analysis

 A1 =
Remarks Similarly other constants A2, A3, …, An can be found, viz.,

A2 =
………………………………………...
………………………………………...

An =
Substituting these values of A0, A1, A2,…., An in (1), we have

f(x) = ….

…+ (2)
which is called Langrange’s interpolation formula.
Another form of this formula can be obtained by dividing both sides of (2) by (x – x0)(x – x1)
…(x – xn)

…+
This is the other form of Lagrange’s interpolation formula.
Example 1 : Use Lagrange’s formula to find y(5) from the following data :
y(1) = 3, y(3) = 0, y(4) = 30, y(6) = 120.
Solution : The given data can be arranged as

x 1 3 4 6
y = f(x) 3 0 30 120
using Lagrange’s interpolation formula, we get

y = f(5) =

y(5) =
Interpolation with Unequal Intervals 147

Ans.
Example 2 : Given the values
x 5 7 11 13 17
f(x) 150 392 1452 2366 5202
evaluate f(9) using Lagrange’s formula. Remarks
Solution : Here x0 = 5, x1 = 7, x2 = 11, x3 = 13, x4 = 17
and y0 = 150, y1 = 392, y2 = 1452, y3 = 2366, y4 = 5202
According to Lagrange’s Interpolation formula for unequal intervals

f(x) = ….

…+
Put the values of xi,  i = 1,2,3,4, and x = 9, we get

f(9) =

Example 3 : Find the function f(x) for values of x are given as


f(1) = 4, f(2) = 5, f(7) = 5, f(8) = 4.
and also the value of x for which f(x) is maximum or minimum.
Solution : The given values of x and f(x) are :
x: 1 2 7 8
f(x): 4 5 5 4
By application of Lagrange’s formula, we get
148 Programming in C and Numerical Analysis

Remarks

Now, we find for maximum or minimum value of f(x),


f (x) = 0

i.e.

(ve). Hence maximum value at x = 4.5.


10.4 DIVIDED DIFFERENCES
Definition : Let (x0, y0), (x1, y1), (x2, y2),….,(xn, yn) be a given set of (n + 1) points.
The first divided differences are defined by the following relations

………………...
…………………

The second divided differences are defined by

and so on.
The third divided differences are defined by

and so on.
In general the nth divided difference is defined by
Interpolation with Unequal Intervals 149

The divided difference table is given below :

x y First Second Third Fourth


div. diff. div. diff. div. diff. div. diff.
x0 y0
[x0, x1]
x1 y1 [x0, x1,x2]
[x1, x2] [x0, x1,x2, x3]
x2 y2 [x1, x2,x3] [x0, x1,x2, x3, x4]
[x3, x4] [x1,x2, x3, x4]
x3 y3 [x2, x3,x4]
[x3, x4]

Example 1 : The divided difference table for the following table Remarks

x 1 0 2 4
y 0 1 9 65

Solution :
x y First div. Second div. Third div.
diff. diff. diff.
1 0

0 1

2 9

4 65

Example 2 : if f(x) = , then find the divided difference [a, b] and [a, b, c].

Solution : Here, we have x = a, b, c and the corresponding y values are


Thus, we get
150 Programming in C and Numerical Analysis

10.5 NEWTONS’S DIVIDED DIFFERENCES FORMULA


Let y(x) be a function taking values y0, y1, y2,….,yn corresponding values x0, x1, x2,…,xn. Then the
Newton’s divided difference formula is given by
y(x) = y0 + (x – x0) [x0, x1] + (x – x0) (x – x1) [x0, x1, x2] + (x – x0) (x – x1) (x – x2)
[x0, x1, x2, x3] + …+(x – x0)(x – x1)…(x – xn-1) [x0, x1, x2,…,xn].
Remarks

Proof : we have (1)


From (1), we get
y = y0 + (x – x0) [x, x0]

Also, [x, x0, x1] =


Therefore, [x, x0] = [x0, x1] + (x – x1) [x, x0, x1] (2)
Putting the value of [x, x0] in (1), we get
y = y0 + (x – x0) ([x0,x1] + (x – x1) [x, x0, x1])
= y0 + (x – x0) [x0, x1] + (x – x0) (x – x1) [ x, x0, x1]
Proceeding like this we get the result
y(x) = y0 + (x – x0) [x0, x1] + (x – x0) (x – x1) [x0, x1, x2] + (x – x0) (x – x1) (x – x2)
[x0, x1, x2, x3] + …+(x – x0)(x – x1)…(x – xn-1) [x0, x1, x2,…,xn].
Which is known as Newton’s divided difference formula.

Example 1 : Using the following table find y(x) as a polynomial in x.

x 0 1 2 3
y(x) 1 0 1 10

Solution : The divided difference table is given below

x y First div. Second div. Third div.


diff. diff. diff.
x0 = 0 y0 = 1
Interpolation with Unequal Intervals 151

x1 = 1 y1 = 0

x2 = 2 y2 = 1

x3 = 3 y3 = 10

From the table we have


y0 = 1, [x0, x1] = 1, [x0, x1,x2] = 1, and [x0, x1, x2, x3] = 1
Newton’s divided difference formula is
y(x) = y0 + (x – x0) [x0, x1] + (x – x0) (x – x1) [x0, x1, x2]
+ (x – x0) (x – x1) (x – x2) [x0, x1, x2, x3]
Therefore, y(x) = 1 + (x – 0) (1) + (x – 1) (1) + (x – 0) (x – 1) (x – 2) 1 Remarks
= 1 – x + (x2 – x) + (x3 – 3x2 + 2x)
Therefore, y(x) = x3 – 2x2 + 1

Example 2 : Given the values

x 5 7 11 13
y 150 392 1452 2366

Evaluate y(9) using Newton’s divided differences formula.


Solution : Using the Newton’s divided difference formula.
The divided difference table is given below :

x y First div. Second div. Third div.


diff. diff. diff.
x0 = 5 y0 = 150
121
x1 = 7 y1 = 392 24
265 1
x2 = 11 y2 = 1452 32
457
x3 = 13 y3 = 2366

The Newton’s divided difference formula is


y(x) = y0 + (x – x0) [x0, x1] + (x – x0) (x – x1) [x0, x1, x2]
+ (x – x0) (x – x1) (x – x2) [x0, x1, x2, x3]
put x = 9. Then
y(9) = 150 + (9 – 5)121 + (9 – 5)(9 – 7)24 + (9 – 5)(9 – 7) (9 – 11)1
= 150 + 484 + 192 – 16 = 810
Therefore y(9) = 810
152 Programming in C and Numerical Analysis

Example 3 : Find the polynomial of the lowest possible degree which assumes the values 2, 3, 12,
147 when x has the values 0, 1, 2, 5 respectively and also find f(x) as a polynomial on powers of (x –
5).
Solution : Lets first make a divided difference table from the above data

x y First div. diff. Second div. Third div.


diff. diff.
0 2
(32)/10 = 1
1 3 (91)/20 = 4
(123)/21 = 9 (94)/50=1
2 12 (459)/51= 9
(14712)/52 = 45
5 147

We have x0 = 0, f(x0) = 2, [x0, x1] = 1, [x0, x1, x2] = 4, [x0, x1, x2] = 1
So by Newton’s divided difference formula, we have
Remarks y = f(x) = f(x0) + (x – x0) [x0, x1] + (x – x0) (x – x1) [x0, x1, x2]
+ (x – x0) (x – x1) (x – x2) [x0, x1, x2, x3]
= 2 + (x – 0)1 + (x – 0) (x – 1)4 + (x – 0) (x – 1) (x – 2)1
= x3 + x2 – x + 2

To express the polynomial f(x) in powers of (x – 5), we divide x3 + x2 – x + 2 successively by (x – 5)


1 1 1 2
5
- 5 30 145
5 1 6 29

- 5 55
5 1 11

- 5
5 1

-
1

Thus f(x) = x3 + x2 – x + 2
= (x – 5)3 + 16 (x – 5)2 + 84 (x – 5) + 147

10.6 HERMITE INTERPOLATION FORMULA


Interpolation with Unequal Intervals 153

The Hermite interpolating polynomial interpolates not only the function f(x) but also its (certain
order) derivatives at a given set of tabular points. The simple interpolating conditions are given in (1).
We now give an explicit expression for the interpolating polynomial satisfying (1), that is

(1)

where Ai(x) and Bi(x) are polynomials in x of degree 2n + 1, which are to be determined.
Using condition (1), we get

 (3)
From (2), we have
Remarks

Using conditions (1), we get

 = 0 for all i and (4)


Now, we take Ai(x) = Ci(x) [Li(x)]2 and 2
Bi(x) = Di(x)[Li(x)] ,

where
Since [Li(x)]2 is of degree 2n and Ai(x), Bi(x) are of degree (2n + 1), therefore Ci(x) and Di(x) are
both linear polynomials.
Let Ci(x) = ai + bix
Di(x) = ci + dix
Ai(xj) = (ai + bix) [Li(xj)]2 (5)
and Ai(xj) = bi[Li(xj)] + (ai + bixj). 2Li(xj).Li(xj)
2

using conditions (3), (4) and taking Li(xi) = 1, we get


ai + bixi = 1
and bi + (ai + bixi) 2Li(xi) = 0
On Solving, we get
bi = 2Li(xi)
and ai = 1 + 2 xi Li(xi)
154 Programming in C and Numerical Analysis

As Ai(x) = (ai + bix)[Li(x)]2


 Ai(x) = [1+ 2xi Li(xi)  2x Li(xi)] [Li(x)]2
= [1 – 2(x – xi) Li(xi)] [Li(x)]2 (6)
Now, Bi(xj) = (ci + dixj) [Li(xj)]2 (7)
Bi(xj) = di[Li(xj)]2 + (ci + dixj).2[Li(xj)] [Li(xj)]
Using (3) and (4) and Li(xi) = 1, we get
c i + d i xi = 0
di + (ci + dixi) 2Li(xi) = 1
On solving, we get di = 1 and ci = xi
As Bi(x) = (ci + dix) [Li(x)]2
Bi(x) = (xi + x) [Li(x)]2 (8)
Using (6) and (8) in (2), we get

which is the required Hermite’s interpolation formula.


Remarks
Example 1 : Obtain the Hermite interpolating polynomial which fits the data :

x f(x) f (x)
0 0 1
4 2 0

Solution : The Hermite interpolating polynomial is given by

Now
Interpolation with Unequal Intervals 155

 The Hermite polynomial is


H(x) = 0.A0 + 2A1 + 1.B0 + 0.B1
= 2A1 + B0

Exercise 10.1
Question 1 : By using Lagrange’s formula, find the value of
(i) y5 if y1 = 4, y2 = 120, y4 = 340, y6 = 2544
(ii) (ii ) u5 if u0 = 1, u2 = 19, u4 = 49, u6 = 181.
Question 2 : Apply Lagrange’s formula to find the value of f(15) by using the following functional Remarks
values :
x: 10 12 14 16 18 20
f(x): 2420 1942 1497 1109 790 540

Question 3 : Given that = 0.3010, = 0.4771 and = 0.8451, find the value of .

Question 4 : Apply Hermite’s formula to estimate the value of log 3.2 from the following data :

x f(x) = log x

f (x) =
3.0 1.0986 0.3333
3.5 1.2528 0.2857
4.0 1.3863 0.2500

Question 5 : Using the following data , find f(x) as a polynomial :

x: 1 0 2 3 7 10
f(x): 11 1 1 1 141 561
156 Programming in C and Numerical Analysis

Question 6 : Show that

(i) is independent of x, y, z.

(ii) x3 = x + y + z.
Question 7 : Using Newton’s divided difference formula, find f(x) as a polynomial in powers of (x –
6).
x: 1 0 2 3 7 10
f(x): 11 1 1 1 141 561

Question 8 : Given the table :

x: 1 3 4 6 7
yx: 1 27 81 729 2187

Remarks Answers
1 : (i) 1044 (ii) 96.625 2 : 1295 3: 1.5184 4: 1.1631
3 2 3 2
5 : x – 5x + 6x + 1 7 : (x – 6) +13(x – 6) + 54(x – 6) + 73
8 : 209

Keywords : Interpolation for unequal intervals, Lagrange’s interpolation, Newton divided difference
interpolation.

Summary : In this unit we have discussed various types of interpolation for unequal intervals. They
may be Lagrange’s interpolation or Newton’s divided difference interpolation. We also discussed the
Lagrange’s interpolation formula which is a better approximation for the values not equidistant.
Further, we discuss Newton’s divided formula.
Remarks

CHAPTER – XI
NUMERICAL DIFFERENTIATION
11.0 STRUCTURE
11.1 Introduction
11.2 Objective
11.3 Newton’s Difference Formula
11.4 Derivatives Using Sterling Central Difference Formula
11.5 Derivatives Using Bessel’s Central Difference Formula
11.6 Derivative Using Newton’s Divided Difference Formula

11.1 INTRODUCTION
It is the process of calculating or approximate numerical value of derivative of a function f(x).
However, if we do not known the function explicitly but a set of numerical values (x i, yi), i = 0, 1, 2,
…, n is known.
If the values of x are equi-spaced and it is required to find the value of derivative by using
(according as value of a)
(i) Newton’s Forward Interpolation Formula
(ii) Newton’s Backward Interpolation formula
(iii) Sterling Formula for Interpolation Formula
(iv) Bessel’s Formula for Interpolation Formula
It the values of x are not equi-spaced and it is required to find the value of derivative by using
11.2 OBJECTIVE
At the end of this unit students should be able to know
1. Derivative using various interpolation formula
2. Solution of problems using interpolation formula
11.3 NEWTON’S DIFFERENCE FORMULA
11.3.1 Derivatives Using Newton’s Forward Interpolation Formula

Newton’s forward interpolation formula is used for finding the values of near the
beginning of a set of tabulated value
As, we know that Newton’s forward interpolation formula is

+ …… (i)

where 
Differentiating both sides of (i) w.r.t. u, we get

(ii)
158 Programming in C and Numerical Analysis

Now,
Remarks

 (iii)

To find second derivative

(iv)
At x = x0, we have u = 0, So equation (iii) becomes

(v)
Also, equation (v) becomes

(vi)
Example : Given that :
x: 1.1 1.2 1.3 1.4 1.5 1.6
y: 8.403 8.781 9.129 9.451 9.750 10.031

Find at x = 1.1
Solution : The difference table is as under :
x y y 2y 3y 4y 5y
1.1 8.403
0.378
1.2 8.781 0.030
0.348 0.004
1.3 9.129 0.026 0.001
0.322 0.003 0.003
1.4 9.451 0.023 0.002
0.299 0.005
1.5 9.750 0.018
0.281
Numerical Differentiation 159

1.6 10.031

Remarks

To find at x = 1.1 :
Since x = 1.1 lies near the beginning of the table, so we shall use Newton’s forward formula.
Taking x0 = 1.1 and h = 0.1, we have

Putting u = 0 in Newton’s forward formula, we get

(i)

and (ii)
At x0 = 1.1, we have y0 = 8.403, y0 = 0.378, 2y0 = 0.030, 3y0 = 0.004, 4y0 = 0.001 and
 y0 = 0.003,
5

and

11.3.2 Derivatives Using Newton’s Backward Interpolation Formula

Newton’s backward formula is used for find values of the function near the end of a set of
tabulated value
As, we know that Newton’s backward formula is

+ …… (i)

where


Differentiating both sides of (1) w.r.t. u, we get

(ii)

Now,

 (iii)
160 Programming in C and Numerical Analysis

Remarks

To find the second derivative :

(iv)
At x = xn, we get u = 0. So equation (iii) becomes

(v)
Also, equation (iv) becomes

(vi)

Example : Find at x = 0.4 from the following table :

x 0.1 0.2 0.3 0.4


y 1.10517 1.22140 1.34986 1.49182

Solution : We have to find the values of derivatives at x = 0.4, which lies near the end of tabulated
and we use Newton’s Backward Formula

Here h = 0.1, xn = 0.4, =

= 1.49133
11.4 DERIVATIVES USING STERLING CENTRAL DIFFERENCE FORMULA

Sterling formula is useful when u lies between and


By Sterling formula, we have

Differentiating both sides w.r.t. u, we get


Numerical Differentiation 161

(i)

Since  Remarks

Now,

(ii)

To find the second derivative :

i.e.

or (iii)
For tabulated value at x = x0, we have u = 0

and

Example : Use Sterling formula to find at x = 93 from the following :

x 60 75 90 105 120
f(x) 28.2 38.2 43.2 40.9 37.7

Solution : In this problem the value of derivative is required at x = 93 which lies near the middle of
the given values. Hence we can use the sterling’s formula for central difference. Here h = 15, y = f(x)

Let when x = 93,


The difference table is
x y y 2y 3y 4y

60 2 28.2
10.0
75 1 38.2 5.0
5.0 2.3
162 Programming in C and Numerical Analysis

90 0 43.2 7.3 9.7


2.3 6.4
105 1 40.9 0.9
3.2
120 2 37.7
Remarks

11.5 DERIVATIVES USING BESSEL’S CENTRAL DIFFERENCE FORMULA

Bessel’s formula used when u lies between and and also fai u = fai find
From Bessel’s formula, we have

Differentiating both sides w.r.t. u, we get

(i)

Since

Now,
Numerical Differentiation 163

(ii)
To find the second derivative Remarks

(iii)
For tabulated values at x = x0, we have u = 0

 (iv)

and

Example : Find the value of f (x) at x = 0.04 from the following table :

x: 0.01 0.02 0.03 0.04 0.05 0.06


f(x) : 0.1023 0.1047 0.1071 0.1096 0.1122 0.1148

Solution : Let x0 = 0.04, h = 0.01,

At x = 0.04,
Since the value of derivative is required at x = 0.04 which lies near the middle of the tabulated values,
therefore, we shall use one of the central difference formula, we use Bessel’s formula

The difference table is as under :


164 Programming in C and Numerical Analysis

x f(u) f(u) 2f(u) 3f(u) 4f(u)


u
0.01 3 0.1023
0.0024
0.02 2 0.1047 0.0000
0.0024 0.0001
0.03 1 0.1071 0.0001 0.0001
0.0025 0.0000
0.04 0 0.1096 0.0001 0.0001
0.0026 0.0001
0.05 1 0.1122 0.0000
0.0026
0.06 2 0.1148

Remarks From Bessel’s formula, we have

Putting u = 0, we get

11.6 DERIVATIVE USING NEWTON’S DIVIDED DIFFERENCE FORMULA


Newton divided difference formula is used when x are not equi-spaced.
By Newton’s divided difference formula, we have

f(x) = f(x0)+(x – x0) f(x0)+(x – x0)(x – x1) f(x0)+(x – x0)(x – x1)(x – x2) f(x0)
Numerical Differentiation 165

+(x – x0)(x – x1)(x – x2)(x – x3) f(x0) + ….. (i)


Differentiating both sides of (i) w.r.t x, we get

f (x) = f(x0) + (2x – x0 – x1) f(x0) + [3x2 – 2x(x0 + x1 + x2) + x0x1 + x1x2

+ x2x0] f(x0)+[4x3  3x2(x0 + x1 + x2 + x3) + 2x(x0x1 + x1x2

+ x2x3 + x3x0 + x1x3 + x0x2)] f(x0) +…….


Which is required formula for finding the value of f (x) when the values of x are not equispaced.
Example : Find the first derivative of the function y = f(x) tabulated below at the point x = 12

x: 3 5 11 27 34
f(x) : 13 23 899 17315 35606

Solution : Here the values of x are not equi-spaced. Hence we shall use Newton’s divided difference Remarks
formula.
The divided difference table is as under :
x f(x) f(x) 2f(x) 3f(x) 4f(x)
3 13
18
5 23 16
146 1
11 899 40 0
1026 1
27 17315 69
2613
34 35606

Since fourth difference is zero so Newton’s divided difference formula is

f(x) = f(x0)+(x – x0) f(x0)+(x – x0)(x – x1) f(x0)+(x – x0)(x – x1)(x – x2) f(x0)

+(x – x0)(x – x1)(x – x2)(x – x3) f(x0) (i)


Differentiating both sides of (i) w.r.t x, we get

f (x) = f(x0) + (2x – x0 – x1) f(x0) + [3x2 – 2x(x0 + x1 + x2) + x0x1 + x1x2

+ x2x0] f(x0)+[4x3  3x2(x0 + x1 + x2 + x3) + 2x(x0x1 + x1x2

+ x2x3 + x3x0 + x1x3 + x0x2)] f(x0) (ii)


Putting x0 = 3, x1 = 5, x2 = 11, x3 = 27, x4 = 34 and x = 12 in (ii), we get
f (x) = 18 + (2 
 

166 Programming in C and Numerical Analysis

Exercise 11.1
Question 1 : Find the first and second derivatives of f(x) at x = 1.5 if
x: 1.5 2.0 2.5 3.0 3.5 4.0
f(x) : 3.375 7.000 13.625 24.000 38.875 59.000

Question 2 : Find the first and second derivatives of the function tabulated at x = 1.25
x: 1 1.05 1.10 1.15 1.20 1.25
f(x) : 1.0000 1.0247 1.0488 1.0723 1.0954 1.1180

Question 3 : Using Bessel’s formula, find f (7.50) from the following table :
x: 7.47 7.48 7.49 7.50 7.51 7.52 7.53
f(x) : 0.193 0.195 0.198 0.201 0.203 0.206 0.208
Remarks
Question 4 : Given the following pair of values of x and = f(x) :
x: 1 2 4 8 10
y = f(x) : 0 1 5 21 27

Determine numerically the first derivative at x = 4.

Answers 11.1
1. 4.75; 9 2. 0.4428; 0.52 3. 0.223 4. 7.833
Keywords : Forward interpolation, backward interpolation, central interpolation.
Summary : In this unit, we have developed formulas for numerical differentiation using Newton
forward, backward, central and Lagrange’s interpolation formulas. But numerical techniques provide
only approximation to derivative.
Remarks
CHAPTER – XII
NUMERICAL INTEGRATION
12.0 STRUCTURE
12.1 Introduction
12.2 Objective
12.3 Some Quadrature Formula for Equidistant Values of x
12.3.1 General Quadrature Formula
12.3.2 Trapezoidal Rule

12.3.3 Simpson’s rule

12.3.4 Simpson’s th Rule


12.3.5 Weddle’s Rule
12.1 INTRODUCTION
It is the technique or method of approximate the numerical value of a definite integral I =

when f(x) is not known explicitly, but a set of numerical values of functions are known at
some values, these values of x may be equidistant as at non-equidistant. This process of
approximations likewise numerical differentiation, this process is based on finding suitable
interpolation polynomial and integration of it with given limit and this is the principle of numerical
integration.
This method is also applicable some time when f(x) is known, but its integration is not easy to

solve. Example f(x) = , sin x2 etc.


12.2 OBJECTIVE
At the end of this unit students should be able to
1. Use of Trapezoidal rule for integration
2. Use of Simpson’s 1/3rd rule for integration
3. Use of Simpson’s 3/8th rule for integration.
12.3 SOME QUADRATURE FORMULA FOR EQUIDISTANT VALUES OF X
12.3.1 General Quadrature Formula
If f(x) is known at equidistant values of x, firstly we can approximate the f(x) by using Newton’s
forward interpolation formula and then integrate the Newton’s forward formula over n equal intervals
If values of f(x) given at
x0 = a, x1 = a + h, x2 = a + 2h,….,xn = a + nh = b and values of f(x) are y0, y1, y2,….yn respectively.
They n + 1 values, hence we have to find the nth order differences and higher order difference will be
vanishes.

where P(x) is the polynomial from Newton’s forward interpolation polynomial.

Put  x = x0 + hu
168 Programming in C and Numerical Analysis

Hence dx = hdu
Remarks

(i)
Formula (i) is the required general quadrature formula.
12.3.2 Trapezoidal Rule
Put n = 1 in (i) and neglecting the second and higher order difference, we get

(2.1)
Similarly,

(2.2)

(2.3)
…………………………
…………………………

(2.n)
Add (2.1) to (2.n), we get
Hence

(*)

Example 1 : Calculate by Trapezoidal rule an approximate value of by taking 7 equidistant


ordinates and compare with exact value
Solution : Here a = 3 and b = 3 with h = 1. Then the values of f(x) = x3 are as follows :
x f(x) = x3
3 x0 27 y0
Numerical Integration 169

2 x0 + h 8 y1
1 x0 + 2h 1 y2
0 x0 + 3h 0 y3 Remarks
1 x0 + 4h 1 y4
2 x0 + 5h 8 y5
3 x0 + 6h 27 y6

By Trapezoidal rule, we get

= 1[(-27 + 27) + 2[8  1 + 0 + 1 + 8]]


= 0 Answer
Also exact value is given by

Example 2 : Using Trapezoidal rule, calculate the value of the integral

Solution : Take h = 0.2 with x0 = 4.0 and x6 = 5.2

x: 4.0 4.2 4.4 4.6 4.8 5.0 5.2


loge x 1.3863 1.4351 1.4816 1.5260 1.5686 1.6094 1.6486

By Trapezoidal rule, we get

=
= 1.8276

12.3.3 Simpson’s rule


Put h = 2 in (i) of the article of General Quadrature formula, and neglecting the third and higher order
differences, we get

(3.1)
Similarly,
170 Programming in C and Numerical Analysis

(3.2)

(3.3)
Remarks ………………………………..

add all (3.1) to , we get

Example 1 : Using Simpson’s rule to evaluate using six sub-intervals and hence find an
approximate value of loge4.

Solution : Let I =

Here f(x) = , Take h =


x 1 1.5 2 2.5 3 3.5 4
f(x) = y y0=1 y1=0.667 y2=0.500 y3=0.400 y4=0.333 y5=0.286 y6=0.250

By Simpson’s 1/3 rule

= [(1 + 0.250) +(0.667 + 0.400 + 0.286) + 2(0.500 + 0.333)]


= 1.388

I=

I=

Example 2 : Use Simpson’s rule to find by taking 6 sub-intervals.


Solution : Here n = 6, a = 0, b = 0.6, therefore length of the interval is
Numerical Integration 171

The values of x and y = correct to four decimal places are tabulated


x x0 x1 x2 x3 x4 x5 x6
0.0 0.1 0.2 0.3 0.4 0.5 0.6
y0 y1 y2 y3 y4 y5 y6
y= 1.0000 0.9900 0.9608 0.9139 0.8521 0.7788 0.6977

Simpson’s one third rule for n = 6 is given by


Remarks

= 0.5351

Therefore, = 0.5351

12.3.4 Simpson’s th Rule


Put n = 3 in (i) of the article of General Quadrature formula and neglecting forth and higher order
difference, we get

(4.1)
Similarly,

(4.2)

(4.3)
……………………………………….

add all (4.1) to , we get


172 Programming in C and Numerical Analysis

Example 1 : Evaluate by using


(i) Trapezoidal rule
(ii) Simpson’s one-third rule
(iii) Simpson’s three-eighth rule
Solution : We divide the interval (0, 6) into 6 equal parts each of width h = 1. The value of the

function y = f(x) = at each point of the sub-division are given below:

Remarks x0 x1 x2 x3 x4 x5 x6
x: 0 1 2 3 4 5 6
y: 1 0.5 0.2 0.1 0.0588 0.0385 0.0270
y0 y1 y2 y3 y4 y5 y6

(i) By Trapezoidal rule, we have

= 1.4108
(ii) By Simpson’s one-third rule, we have

= 1.3662
(iii) By Simpson’s three-eighth rule, we have

= 1.3571

12.3.5 Weddle’s Rule


Put n = 6 in (i) of the article of General Quadrature formula and neglecting the difference of orders
higher than six, we get
Numerical Integration 173

We know that is nearly small to , hence we replace from , we get

Remarks

(5.1)
Similarly, we can get

(5.2)
…………………………………………………………….

Add all (5.1) to , we get

Exercise 12.1
174 Programming in C and Numerical Analysis

Question 1: Evaluate using

(i) Trapezoidal rule, taking h =

(ii) Simpson’s rule, taking h =

(iii) Simpson’s rule, taking h =

Question 2: Evaluate using Simpson’s th rule.

Question 3: Calculate an approximate value of by


(i) Trapezoidal rule
(ii) Simpson’s rule, using 11 ordinates. Also find the errors.

Remarks Answers 12.1


Question 1: (i) 0.7828 (ii) 0.7854 (iii) 0.7854
Question 2: 1.96125
Question 3: (i) 0.9981; error = 0.0019 (ii) 1.0004; error = 0.0004
Keywords : Trapezoidal rule, Simpson’s 1/3rd rule, Simpson’s 3/8th rule.
Summary : We develop the following formulas
1. Trapezoidal rule (Applicable for all n)
2. Simpson’s 1/3rd rule (Applicable for all even values of n)
3. Simpson’s 3/8th rule (Applicable for values of n divisible by 3).
Remarks

CHAPTER – XIII
SIMULTANEOUS LINEAR ALGEBRAIC EQUATIONS
13.0 STRUCTURE
13.1 Introduction
13.2 Objective
13.3 Method – I : Gauss Elimination Method
13.4 Method – II : Gauss Jordan Method
13.5 Method – III : Triangularization Method
13.6 Method – IV Crout’s Method
13.7 Method – V Cholesky Method or Square Root Method
13.8 Gauss – Jacobi’s Iteration Method
13.9 Gauss – Seidel Iteration Method
13.10 Relaxation Method
13.1 INTRODUCTION
In this unit, we will study different methods of solutions of a Linear System of equations by direct and
indirect methods.
13.2 OBJECTIVE
At the end of this unit the student should be able to know:-
1. Various types of direct methods to solve the linear system
2. Various types of indirect methods to solve the linear system
13.3 METHOD – I : GAUSS ELIMINATION METHOD
Let the system of equation is
a11x + a12y + a13z = b1 (1)
a21x + a22y + b23z = b2 (2)
a31x + a32y + b33z = b3 (3)
Firstly we elimination of x from (1) and (2) by r1, where (if a11  0)

Now, (1)  r1  (2), we get

We can rewrite this as


C22 y + C23 z = d2 (4)
Secondly, we eliminate x from (1) and (3) by using r2 where

Now, (1)  r2  (3), we get

We can rewrite, this equation as


C32 y + C33 z = d3 (5)
Thirdly, we eliminate y from (4) and (5) by using r3 (C22  0), where
176 Programming in C and Numerical Analysis
Remarks

Now (4)  r3  (5), we get

and we get the value of z


By putting value of z in (4), we get y and then by putting value of z and y in (1), we get x.
Example 1 : Solve the following equations by Gauss elimination method
2x + 4y + z = 3
3x + 2y – 2z = 2
x–y+z=6
Solution : The given system of equation is
x–y+z=6 (1)
2x + 4y + z = 3 (2)
3x + 2y – 2z = 2 (3)
Firstly, we eliminate x from (1) and (2) by using r1, where

Now (1)  r1  (2), we get


6y – z =  9 (4)
Secondly, we eliminate x from (1) and (3) by using r2, where

Now, (1) r2  (3), we get


y–z=4 (5)
Thirdly, we eliminate y from (4) and (5) by using r3, where

Now, (4)  r3  (5), we get

Putting the value of z in (4), we get


y – 3 =  4  y = 1
Putting the value of y and z in (1), we get
x+1+3=6 x=3
13.4 METHOD – II : GAUSS JORDAN METHOD
a11x + a12y + a13z = b1 (1)
a21x + a22y + a23z = b2 (2)
a31x + a32y + a33z = b3 (3)
Assume that (a11  0)
Firstly, we elimination of x from (2) and (3), we get
Now,

(2)   (1), and


Simultaneour Linear Algebraic Equations 177
Remarks

(3)   (1), we get


a11x + a12y + a13z = b1 (4)
C22 y + C23 z = d2 (5)
C32 y + C33 z = d3 (6)
Secondly, we elimination of y from equation (4) and (6), we get
Now,

(4)  (5) and (4)  (6) , we get

(7)

(8)

(9)
Thirdly, we elimination of z from (7) and (8), we get

Now, (7)  and (8) 


We get

Example 2 : Solve the system at equations by Gauss Jorgan method :


2x + 3y – z = 5
4x + 4y  3z = 3
2x – 3y + 2z = 2
Solution : The given system at equations
2x + 3y – z = 5 (1)
4x + 4y  3z = 3 (2)
2x – 3y + 2z = 2 (3)
To eliminate x from equation (2) and (3)
Now, (2)  2  (1) and (3)  (1), we get new system as
2x + 3y – z = 5 (4)
2y + z = 7 (5)
2y  z = 1 (6)
To eliminate y from (4) and (6)

Now, (4)   (5) and (6)  (5), we get the new system as
4x – 5z = 11 (7)
2y + z = 7 (8)
z=3 (9)
To eliminate z from (7) and (8)
(7) + 5  (9) and (8)  (9), we get new system as
4x = 4
2y = 4
178 Programming in C and Numerical Analysis

z=3
Hence, the required solution is
x = 1, y = 2 and z = 3
Remarks 13.5 METHOD – III : TRIANGULARIZATION METHOD
Let the system of equation be
a11x + a12y + a13z = b1 (1)
a21x + a22y + a23z = b2 (2)
a31x + a32y + a33z = b3 (3)
This system can be written as in the form AX = B
Where

A= , X=

and B=
Now we assume A = LU

Where L = and U=

 A=

 =
(1) By comparing 11th, 12th and 13th position of both matrix, we get
u11 = a11, u12 = a12 and u13 = a13
(2) By comparing 21st and 31st position of both matrix, we get

and
(3) By comparing 22nd and 23rd position of both matrix, we get

(4) By comparing 23rd position of both matrix, we get


Simultaneour Linear Algebraic Equations 179

(5) Lastly we compare 33rd position of both the matrix, we get


u33 = a33  l31 u13  l32 u23
Now AX = B can be written as Remarks
(LU)X = B or L(UX) = B
Let UX = B, then L(UX) = B

Become LZ = B where Z =
By using LZ = B

= (*)
Comparing the corresponding element of (*), we get z1, z2 and z3
Putting the values of Z in UX = B, we get

= (**)
Comparing the corresponding elements of (**), we get x, y, z.
Example 1 : Solve the system of equation by Triangularisation Method
2x + 3y + z = 9
x + 2y + 3z = 6
3x + y + 2z = 8
Solution : The given system of equations can be written as A X = B (1)
Where

A= ; X= B=
Assume A = LU, where

L= and U=

 = (2)
Comparing the elimination (2)
180 Programming in C and Numerical Analysis

(1) By comparing 11th, 21st and 31st position, we get


l11 = 2, l21 = 1, l31 = 3
(2) Comparing the 12th and 13th position, we get

l11u12 = 3  u12 =

l11u13 = 1 u13 =
Remarks (3) Comparing the 22nd and 32nd position, we get

l21u12 + l22 = 2  l22 = 2  1=

l31u12 + l32 = 1  l32 = 1  3=


(4) Comparing the 23rd position, we get

l21u13 + l22u23 = 3  u23 = =5


(5) Comparing the 33rd position, we get
l31u13 + l32u23 + l33 = 2

l33 = 2  3  (5) = 18
Now AX = Bas LUX = B
Put UX = Z
 LZ = B

By comparing elements, we get


Simultaneour Linear Algebraic Equations 181


Now UX = Z
Remarks

By comparing the corresponding elements, we get

x3 = , x2 = , x1 =
13.6 METHOD – IV CROUT’S METHOD
Let the given system of equations be
a11x + a12y + a13z = b1
a21x + a22y + a23z = b2
a31x + a32y + a33z = b3
This system can be written as
AX = B
where

A= X= B=
This system can be solve using derived matrix [A : B] where

[A : B] =
Where

(i) , when i  j
182 Programming in C and Numerical Analysis

(ii) , when i < j

(iii)

(iv)
Example 1 : Solve the following equations by Crout’s method
2x + 3y + 2z = 2
10x + 3y + 4z = 16
Remarks 3x + 6y + z = 6
Solution : The augmented matrix from the given system of equations is

[A : B] ~
The elements of the derived matrix [A : B] are obtained as follows.
1. Elements of 1st column (Take j = 1 and i j), we get
a11 = a11 = 2, a21 = a21 = 10, a31 = a31 = 3,
2. Elements of 1st row (except a11) : (Take i = 1 and i < j)

a12 = , a13 = = 1, b1 = =1


3. Elements of 2nd column (except a12) (Take j = 2 and i  j)

a22 = a22  a21.a12 = 3  10  


4. Elements of 2nd row i.e., a23, b2 : (Take i = 2 and i < j)

5. Element a33 of 3rd column : (Take j = 3 and i > j)


a33 = a33  a31a13  a32a23

6. Elements b3 of 3rd row : (Take i = 3)


Simultaneour Linear Algebraic Equations 183

Thus, the derived matrix [A : B] =


 Solution of given system of equation is Remarks
z = b3 = 3,
y = b2  a23z

=
x = b1  a12y  a13z

=
Hence, the required solution is x = 1, y = 2, z = 3.
13.7 METHOD – V CHOLESKY METHOD OR SQUARE ROOT METHOD
For solution of the system AX = B with AT = A and A is +ve define matrix then A can be decomposed
into prduct of Lower triangular matrix and its transpose.
 A = LL where L is lower triangular matrix
Then AX  B becomes LLX = B
from LX = Z, we get LZ = B
from LZ = B, we get z1, z2,…,zn and put these values in LX = Z, we get the values of x1, x2,….,xn.
Special Point : Method of finding Inverse
A = LL
A-1 = (LL)-1 = (L)-1 L-1 = (L-1) L-1
for find of A-1, we have to need L-1, then we use A-1 = (L-1) L-1.
Example 1 : Find the inverse of the matrix

A= by Cholesky’s method.
Solution : here A is symmetric matrix

A = LL where L =
184 Programming in C and Numerical Analysis

or = (*)
(1) Comparing the 11 , 12th and 13th elements of (*), we get
th

=1  l11 = 1
l11l21 = 2  l21 = 2
l11l31 = 6  l31 = 6
(2) Comparing the 22nd and 23rd elements of (*), we get

=5  l22 = 1
l21l31 + l22l32 = 15  l32 = 3
(3) Comparing the 33rd element of (*), we get

= 46  l33 = 1
Remarks

 L=
To find L-1

Let L-1 =
Since LL-1 = I

 =

=
(1) Comparing 11th, 21st and 31st position, we get

= 1, = 2 and =0
(2) Comparing 22nd and 32nd position, we get

= 1, = 3
(3) Comparing 33rd position, we get

=1
Simultaneour Linear Algebraic Equations 185

 L-1 =

(L-1) =
But A = LL  A-1 = (L-1) L-1

= =
Example 2 : Solve the following system of equations using Cholesky method :
x+y+z=5
x + 2y + 2z = 6
x + 2y + 3z = 8
Solution : The above system can be written as AX = B
Remarks

where A=
Let A = LL where L is lower triangular matrix. Then

or
Elements of L can be obtained by employing the following steps :
Step I : Comparing the elements of 1st row : (11th, 21st, 31st position)

=1  l11 = 1
l11l21 = 1  l21 = 1
l11l31 = 1  l31 = 1
Step II : Comparing the elements of 2nd row : (22nd and 23rd position)

=2  l22 = 1

 l32 = 1
Step III : Comparing the elements of 3rd row : (33rd position)

=3  l33 = 1
186 Programming in C and Numerical Analysis

Hence L=
Now, AX = B
or (LL)X = B
or L(LX) = B
or LZ = B, where Z = LX
Consider LZ = B


 z1 = 5
z1 + z2 = 6  z2 = 1
z1 + z2 + z3 = 8  z3 = 2

 Z=
Now, LX = Z
Remarks


 x+y+z=5
y+z=1
z=2
Solving the above equations, we have z = 2, y = 1, x = 4
Hence the solution of given system of equations is x = 4, y = 1, z = 2.
13.8 GAUSS – JACOBI’S ITERATION METHOD
Consider a linear system (we take, three equation in 3 unknowns) given by
a11x + a12y + a13z = b1
a21x + a22y + a23z = b2 (1)
a31x + a32y + a33z = b3
In which the diagonal elements a11, a22, a33 do not vanish and they are large as compared to other
coefficients. Otherwise the equations should be rearranged so that the conditions are satisfied. Solve
for x, y, z respectively and the system can be written as

(i)

(ii)
Simultaneour Linear Algebraic Equations 187

(iii)
We start with the trial solution x = x(0), y = y(0), z = z(0) (initial approximation) and substitute these
in the R.H.S. of (i), (ii) and (iii) to obtain the first approximation to the solution denoted by

(iv)

The second approximation is obtained by substituting the set of values as in (iv) into the equations
(i), (ii) and (iii). These are denoted by, x(2), y(2), z(2).
Similarly, if x(j), y(j), z(j) are a system of jth approximations, then the next approximation is given by the
formula

Remarks

, j = 0, 1, 2, 3, 4…..
The procedure is continued till the difference between two consecutive approximations is negligible.
Note :
In the absence of any better estimates as x(0) = y(0) = z(0) these are assumed as x(0) = y(0) = z(0) = 0.
Example : We consider the equations
3x + 20y – z = 18
2x  3y + 20z = 25
20x + y – 2z = 17
After partial pivoting we can rewrite the system as follows :
20 x + y – 2z = 17
3x + 20 y – z = 18 (1)
2x – 3y + 20 z = 25
Solve for x, y, z respectively

(2)

we start from an initial approximation


188 Programming in C and Numerical Analysis

where (x(1), y(1), z(1)) = (0.85, 0.9, 1.25) are the first approximated values.
Putting these values on the right hand sides of the equations (2), we obtain

The second approximated values of x, y, z are


(x(2), y(2), z(2)) = (1.0200, 0.965, 1.03).
Substituting these values on the right hand sides of the equations (2), we have
x = x(3) = 1.00125
y = y(3) = 1.0015
z = z(3) = 1.0032
Continuing this process, we get
Remarks The values in the 5th and 6th iterations being practically the same, we can stop the iterations. Hence the
solution is
Therefore, x = 1, y = 1, z = 1.
13.9 GAUSS – SEIDEL ITERATION METHOD
This is a modification of Jacobi’s method. As before the system of equations
a11x + a12y + a13z = b1
a21x + a22y + a23z = b2 (1)
a31x + a32y + a33z = b3
is written as

(i)

(ii)

(iii)
Here also we start with the initial approximation x(0), y(0), z(0) for x, y, z respectively. Substituting y =
y(0), z = z(0) in (i), we get

Then putting x = x(1), z = z(0) in (ii), we have


Simultaneour Linear Algebraic Equations 189

Then putting x = x(1), y = y(1) in (iii), we have

and so on, that is, as soon as a new approximation for an unknown is found, it is immediately used in
the next step.
In general, if are a system of jth approximation, then the next approximation is given by
the formula

, j = 0, 1, 2, 3…..
The process of iteration is repeated till the values of x1, x2, x3 are obtained to desired degree of
accuracy.
Example : Apply Gauss – Seidel iteration method to solve the equations
3x1 + 20x2  x3 = 18
2x1  3x2 + 20x3 = 25
Remarks
20x1 + x2  2x3 = 17
and

(i)

x2 = [18  3x1 + x3] (ii)

x3 = [25  2x1 + 3x2] (iii)

Initial approximation :
First iteration :

Taking in (i) we get = 0.85

Taking x1 = = 0.85, in (ii), we have

Taking x1 = = 0.85, x2 = = 1.0275 in (iii), we obtain

Therefore,
190 Programming in C and Numerical Analysis

Second Iteration :

Similarly, in third iteration, we get

The values in the 2nd and 3rd iterations being practically the same, we can stop the iterations. Hence the
solution is x1 = 1, x2 = 1, x3 = 1
13.10 RELAXATION METHOD
The given system of equations as :
a11x + a12y + a13z = b1
a21x + a22y + a23z = b2
a31x + a32y + a33z = b3
We can apply this method properly and efficiently if the diagonal elements of the coefficient matrix
dominate the other coefficients in the corresponding row
i.e., in the equations (1)
| a11 |  | a12 | + | a13 |
| a22 |  | a21 | + | a23 |
| a33 |  | a31 | + | a32 |
where the (>) shows that validity of > for at least one row should be valid.
Step I : Define the residuals Rx, Ry and Rz as follows :
Rx = b1 – a11x – a12y – a13z
Remarks Ry = b2 – a21x – a22y – a23z
Rz = b3 – a31x – a32y – a33z
Step II : Prepare the operation table as shown below :
The operation table is

Rx Ry Rz


x = 1 a11 a21 a31
y = 1 a12 a22 a32
z = 1 a13 a23 a33
This table is negative of the transpose of the coefficient matrix.
Step III : Prepare the relaxation table as explained below :
The relaxation table is
Rx Ry Rz
x=y=z=0 b1 b2 b3 (i)
b1a11, x  a12.0 b2a21.x a22.0 b3a31.x  a32.0 (ii)

z = a13.0 a23.0 a33.0 (iii)


Assume x = y = z = 0 and calculate the initial residuals, i.e., b 1, b2 and b3. Identify the
(numerically) largest residual in (i). (say Rx),
Simultaneour Linear Algebraic Equations 191

To reduce it give an increment and the resulting residuals are shown in (ii). Of these
identify the (numerically) largest residual in (ii) (say R z) again, and give an increment z =
numerically largest residual in (ii), to get the results in (iii). Repeat this process in the same way, Stop
when all the residuals have been reduced almost to zero.
Step V : Add the increments in x, y, z separately to get the desired solution, that is, x = x, y =
y, z = z.
Example : Solve by Relaxation method, the following equations :
9x + 3y + 4z + 100 = 0
x – 7y + 3z + 80 = 0
2x + 3y -5z + 60 = 0

Rx Ry Rz
x=y=z=0 100 80 60
100 – 9  11.111 + 3  80+11.1117 60+211.111+30
0 + 4  0 = 0.001  5 
=11.111
x = 11.111
100 – 9  80 + 11.111 – 7 60 + 2  11.111 + 3 
 13.016+30 13.016 – 5  0 =
=13.016
= 0.001 121.270
y = 13.016
100 – 9  11.111 + 3 80 + 11.111 – 7 60 + 2  11.111 + 3 
 13.016 + 4  24.254 13.016 + 3  24.254 = 13.016  5  24.254 =
z = 24.254 = 136.065 72.761 0.000
100 – 9  26.229 + 3 80 + 26.229 – 7  60 + 2  26.229 + 3 
 13.016 + 4  24.254 13.016 + 3  24.254 = 13.016 5  24.254 = Remarks
x = 15.118 = 0.003 87.870 30.236
100 – 9  26.229 + 3 80 + 26.229 – 7  60 + 2  26.229 + 3 
 25.570 + 4  24.254 25.570 + 3  24.254 = 25.570 – 5  37.834 =
y = 12.554 = 37.665 0.001 0.002
100 – 9  26.229 + 3 80 + 26.229  7  60 + 2  26.229 + 3 
 25.570 + 4  37.834 25.570 + 3  37.834 = 25.570 – 5  37.834 =
z = 13.580 = 91.985 40.741 0.002
100 – 9  36.450 + 3 80 + 36.450 – 7  60 + 2  36.450 + 3 
 25.570 + 4  37.834 25.570 + 3  37.834 = 25.570 – 5  37.834 =
x = 10.221 = 0.004 50.962 20.440
100 – 9  36.450 + 3 80 + 36.450  7  60 + 2  36.450 + 3 
 32.850 + 4  37.834 32.850 + 3  37.834 = 32.850 – 5  37.834 =
y = 7.280 = 21.836 0.002 42.280
100 – 9  36.450 + 3 80 + 36.450 – 7  60 + 2  36.450 + 3 
 32.850 + 4  46.290 32.850 + 3  46.290 = 32.850 – 5  46.290 =
z = 8.456 = 55.660 25.370 0.0001
100 – 9  42.634 + 3 80 + 42.634 – 7  60 + 2  42.634 + 38 
 32.850 + 4  46.290 32.850 + 3  46.290 = 32.850 – 5  46.290 =
x = 6.184 = 0.004 31.554 12.368
192 Programming in C and Numerical Analysis

100 – 9  42.634 + 3 80 + 42.634  7  60 + 2  42.634 + 3 


 37.358 + 4  46.290 37.358 + 3  46.290 = 37.358 – 5  46.290 =
y = 4.508 = 13.528 0.002 25.892

100 – 9  42.634 + 3 80 + 42.634 – 7  60 + 2  42.634 + 3 


 37.358 + 4 51.468 37.358 + 3  51.468 = 37.358 – 5  51.468 =
z = 5.178 = 34.240 15.532 0.002

100 – 9  46.438 + 3 80 + 46.438 – 7  60 + 2  46.438 + 3 


 37.358 + 4  51.468 37.358 + 3  51.468 = 37.358 – 5  51.468 =
x=3.804 = 0.004 19.336 7.610

100 – 9  46.438 + 3 80 + 46.438 – 7  60 + 2  46.438 + 3 


 40.120 + 4  51.468 40.120 + 3  51.468 = 40.120 – 5  51.468 =
y = 2.762 = 8.290 0.002 15.896
100 – 9  46.438 + 3 80 + 46.438 – 7  60 + 2  46.438 + 3 
Remarks  40.120 + 4  54.647 40.120 + 3  54.647 = 40.120 – 5  54.647 =
= 3.179
= 21.006 9.539 0.001
z = 3.179
100 – 9  48.772 + 3 80 48.772 – 7  40.120 60 + 2  48.772 + 3 
 40.120 + 4  54.647 + 3  54.647 = 11.873 40.120 – 5  54.647 =
x = 2.334 = 0.000 4.669
100 – 9  48.772 + 3 80 + 48.772 – 7  60 + 2  48.772 + 3 
 41.816 + 4  54.647 41.816 + 3  54.647 = 41816 – 5  54.647 =
y = 1.696 = 5.088 0.001 9.757

100 – 9  48.772 + 3 80 + 48.772 – 7  60 + 2  41.816 – 5 


 41.816 + 4  56.598 41.816 + 3  56.598 = 56.598 = 0.002
z = 1.951 = 12.892 5.854

100 – 9  50.204 + 3 80 + 50.204 – 7  60 + 2  50.204 + 3 


 41.816 + 4  56.598 41.816 + 3  56.598 = 41.816 – 5  56.598 =
x = 1.432 = 0.004 7.286 2.866
100 – 9  50.204 + 3 80 + 50.204 – 7  60 + 2  50.204 + 3 
 42.857 + 4  56.598 42.857 + 3  56.798 = 42.857 – 5  56.598 =
= 1.041
= 3.127 0.001 5.989
y = 1.041
100 – 9  50.204 + 3 80 + 50.204 – 7  60 + 2  50.204 + 3 
 42.857 + 4  57.796 42.857 + 3  57.796 = 42.857 – 5  57.796 =
= 1.198
= 7.919 3.593 0.001
z = 1.198
100 – 9  51.084 + 3 80 + 51.084  7  60 + 2  51.084 + 3 
 42.857 + 4  57.796 42.857 + 3  57.796 = 42.857 – 5  57.796 =
= 0.880
= 0.001 4.473 1.759
x = 0.880
Simultaneour Linear Algebraic Equations 193

100 – 9  51.084 + 3 80 + 51.084 – 7  60 + 2  51.084 + 3 


 43.496 + 4  57.796 43.496 + 3  57.796 = 0 43.496 – 5  57.796 =
y = 0.639 = 1.916 3.676

100 – 9  51.084 + 3 80 + 51.084 – 7  60 + 2  51.084 + 3 


 43.496 + 4  58.531 43.496 + 3  58.531 = 43.496 – 5  58.531 =
z = 0.735 = 4.856 2.205 0.001

100 – 9  51.624 + 3 80 + 51.624 – 7 60 + 2  51.624 + 3 


 43.496 + 4  58.531 43.496 + 3  58.531 = 43.496 – 58.531 = 1.081
x=0.540 = 0.004 2.745

100 – 9  51.624 + 3 80 + 51.624 – 7  60 + 2  51.624 + 3 


 43.888 + 4  58.531 43.888 + 3  58.531 = 43.888 – 5  58.531 =
y = 0.392 = 1.172 0.001 2.257

100 – 9  51.624 + 3 80 + 51.624 – 7  60 + 2  51.624 + 3 


 43.888 + 4  58.982 43.888 + 3  58.982 = 43.888 – 5  58.982 = Remarks
z = 0.451 = 2.976 1.354 0.002
100 – 9  51.955 + 3 80 + 51.955 – 7  60 + 2  51.955 + 3 
 43.888 + 4  58.982 43.888 + 3  58.982 = 43.888 – 5  58.982 =
= 0.331
= 0.003 1.685 0.664
x = 0.331
100 – 9  51.955 + 3 80 + 51.955 – 7  60 + 2  51.955 +
 44.129 + 4  58.982 44.129 + 3  58.982 = 344.129  5  58.982
= 0.241
= 0.720 0.002 = 1.387
y = 0.241
100 – 9  51.955 + 3 80 + 51.955 – 7  60 + 2  51.955 + 3 
 44.129 + 4  59.259 44.129 + 3  59.259 = 44.129 – 5  59.259 =
z = 0.277 = 1.828 0.829 0.002
100 – 9  52.158 + 3 80 + 52.158 – 7  60 + 2  52.158 + 3 
 44.129 + 4  59.259 44.129 + 3  59.259 = 44.129 – 5  59.259 =
x = 0.203 = 0.001 1.032 0.408

100 – 9  52.158 + 3 80 + 52.158 – 7  60 + 2  52.158 + 3 


 44.276 + 4  59.259 44.276 + 3  59.259 = 44.276 – 5  59.259 =
= 0.147
= 0.442 0.003 0.849
y = 0.147
100 – 9  52.158 + 3 80 + 52.158 – 7  60 + 2  52.158 + 3 
 44.276 + 4  59.429 44.276 + 3  59.429 = 44.276  5
z = 0.170 = 1.222 0.513 

100 – 9  52.283 + 3 80 + 52.283 – 7  60 + 2  52.283 + 3 


 44.276 + 4  59.429 44.276 + 3  59.429 = 44.276 – 5  59.429 =
x = 0.125 = 0.003 0.638 0.249

100 – 9  52.283 + 3 80 + 52.283 – 7  60 + 2  52.283 + 3 


 44.367 + 4  59.429 44.367 + 3  59.429 = 44.367 – 5  59.429 =
y = 0.091 = 0.270 0.001 0.522
194 Programming in C and Numerical Analysis

100 – 9  52.283 + 3 80 + 52.283 – 7  60 + 2  52.283 + 3 


 44.367 + 4  59.533 44.367 + 3  59.533 = 44.367 – 5  59.533 =
z = 0.104 = 0.686 0.313 0.002

100 – 9  52.359 + 3 80 + 52.359 – 7  60 + 2  52.359 + 3 


 44.367 + 4  59.533 44.367 + 3  59.533 = 44.367 – 5  59.533 =
x = 0.076 = 0.002 0.389 0.154

100 – 9  52.359 + 3 80 + 52.359 – 7  60 + 2  52.359 + 3 


 44.423 + 4  59.533 44.423 + 3  59.533 = 44.423 – 5  59.533 =
y = 0.056 = 0.170 0.003 0.322
100 – 9  52.359 + 3 80 + 52.359 – 7  60 + 2  52.359 + 3 
 44.423 + 4  59.597 44.423 + 3  59.597 = 44.423 – 5  59.597 =
z = 0.064 = 0.426 0.189 0.002
100 – 9  52.406 + 3 80 + 52.406 – 7  60 + 2  52.406 + 3 
Remarks  44.423 + 4  59.597 44.423 + 3  59.597 = 44.423 – 5  59.597 =
x = 0.047 = 0.003 0.236 0.096
100 – 9  52.406 + 3 80 + 52.406 – 7  60 + 2  52.406 + 3 
 44.457 + 4  59.597 44.457 + 3  59.597 =  44.457 -  59.597 =
y = 0.034 = 0.105 0.002 0.198
100 – 9  52.406 + 3 80 + 52.406 – 7  60 + 2  52.406 + 3 
 44.457 + 4  59.637 44.457 + 3  59.637 = 44.457 – 5  59.637 =
z = 0.040 = 0.265 0.118 0.002
100 – 9  52.435 + 3 80 + 52.435 – 7  60 + 2  52.435 + 3 
 44.457 + 4  59.637 44.457 + 3  59.637 = 44.457 – 5  59.637 =
x = 0.029 = 0.004 0.147 0.056
100 – 9  52.435 + 3 80 + 52.435 – 7  60 + 2  52.435 + 3 
 44.478 + 4  59.637 44.478 + 3  59.637 = 44.478 – 5  59.637 =
y = 0.021 = 0.067 0.000 0.119
100 – 9  52.435 + 3 80 + 52.435 – 7  60 + 2  52.435 + 3 
 44.478 + 4  59.661 44.478 + 3  59.661 = 44.478 – 5  59.661 =
z = 0.024 = 0.163 0.072 0.001
100 – 9  52.453 + 3 80 + 52.453 – 7  60 + 2  52.453 + 3 
 44.478 + 4  59.661 44.478 + 3  59.661 = 44.478 – 5  59.661 =
x = 0.018 = 0.001 0.090 0.035
100 – 9  52.453 + 3 80 + 52.453 – 7  60 + 2  52.453 + 3 
 44.491 + 4  59.661 44.491 + 3  59.661 = 44.491 – 5  59.661 =
y = 0.013 = 0.040 0.001 0.074
100 – 9  52.453 + 3 80 + 52.453 – 7  60 + 2  52.453 + 3 
 44.491 + 4  59.676 44.491 + 3  59.676 = 44.491 – 59.676 =
z = 0.015 = 0.100 0.044 0.001

As all the residuals have reduced to almost zero so we stop and x, y and z are added.
x = 11.111 + 15.118 + 10.221 + 6.184 + 3.804 + 2.334 + 1.432 + 0.880 + 0.540
Simultaneour Linear Algebraic Equations 195

+ 0.331 + 0.203 + 0.125 + 0.076 + 0.047 + 0.029 + 0.018 = 52.453

y = 13.016 + 12.554 + 7.280 + 4.508 + 2.762 + 1.696 + 1.041 + 0.639 + 0.392
+ 0.241 + 0.147 + 0.091 + 0.056 + 0.034 + 0.021 + 0.013 = 44.491

z = 24.254 + 13.580 + 8.456 + 5.178 + 3.179 + 1.951 + 1.198 + 0.735 + 0.451
+ 0.277 + 0.170 + 0.104 + 0.064 + 0.040 + 0.024 + 0.015 = 59.676

EXERCISE – 13.1
Question 1 : Solve the following equations by Gauss Elimination method :
(i) 4x + 3 y + 2z = 8
x + y + 2z = 7
3x + 2y + 4z = 13

(ii) 10x + 3y + z = 67 Remarks


2x + 5y + 2z = 10
3x – 2y + 5z = 40
Question 2 : Solve the following equations by Gauss-Jordan method :
(i) 2x + y + 4z = 12
4x + 11y – z = 33
8x – 3y + 2z = 20
(ii) 2x1 + 4x2 + x3 = 3
3x1 + 2x2  2x3 = 3
x1  x2 + x3 = 6
Question 3 : Solve the following equations by Triangularization (LU decomposition) method :
(i) 2x1 + 4x2 + 3x3 = 9
3x1 + x2  2x3 = 1
x1  x2 + x3 = 6
(ii) x1 + x2 + 3x3 = 10
3x1 + 2x2 + 4x3 = 20
3x1 + 5x2  x3 = 30
Question 4 : Solve the following equations by Crout’s method :
(i) 2x + y + z = 6
x + 2y + 3z = 11
3x + 4y + z = 1
(ii) 1.2x + 3.4y + z = 7.22
x + 2.5y + 2z = 11.90
3.4x + y + 2.5z = 4.81
Question 5 : Find the inverse of the following matrices by Cholesky’s method :

(i) (ii)
Question 6 : Solve the following equations using Cholesky’s method :
(i) 4x + 2y + 14z = 14
2x + 17y – 5z = 101
196 Programming in C and Numerical Analysis

14x – 5y + 83z = 155


(ii) 9x + 6y + 12z = 17.4
6x + 13y + 11z = 23.6
12x + 11y + 26z = 30.8
Question 7 : Solve the following equations by Jacobi’s method :
(i) 5x + 2y + z = 12
x + 4y + 2z = 15
x + 2y + 5z = 20
(ii) 5x – y + z = 10
2x + 4y = 12
x + y + 5z = 1
Question 8 : Solve the following equations by Gauss-Seidel method :
(i) 10x + y + z = 12
2x + 10y + z = 13
2x + 2y + 10z = 14
Remarks (ii) 10x1 + x2 + x3 = 6
x1 + 10x2 + x3 = 6
x1 + x2 + 10x3 = 6
Question 9 : Solve the following equations by relaxation method :
(i) 10x – 2y – 2z = 6
x + 10y – 2z = 7
x  y + 10z = 8
(ii) 9x – y + 2z = 9
x + 10y – 2z = 15
2x – 2y – 13z = 17
ANSWERS – 13.1
Question 1 : (i) (1, 2, 3) (ii) (7, 2, 3)
Question 2 : (i) (3, 2, 1) (ii) (2, 1, 3)
Question 3 : (i) (2, 1, 3) (ii) (2, 5, 1)
Question 4 : (i) (2, 3, 5) (ii) (3.1, 1.6, 5.5)

Question 5 : (i) (ii)


Question 6 : (i) (3, 6, 1) (ii) (0.6, 1.2, 0.4)
Question 7 : (i) (1, 2, 3) (ii) (2.556, 1.722, 1.055)

Question 8 : (i) (1, 1, 1) (ii)


Question 9 : (i) (1, 1, 1) (ii) (0.9638, 1.6522, 1.215)

Keywords:-
Simultaneour Linear Algebraic Equations 197

Gauss Elimination method, Gauss-Jordan method, Triangularization (LU decomposition), Crout’s

method, Cholesky’s method, Jacobi’s method, Gauss-Seidel method, relaxation method

Summary :-

We have discussed various direct or indirect methods of solving system of linear equations with

suitable examples and exercise .


CHAPTER – XIV Remarks

EIGEN VALUE PROBLEMS


14.0 STRUCTURE
14.1 Introduction
14.2 Objective
14.3 Properties of Eigen Values
14.4 To find eigen vectors
14.5 Power Method
14.6 Jacobi’s Method for Symmetric Matrix
14.7 Given’s Method
14.8 House-Holder’s Method
14.9 QR Method
14.10 Lanczo’s Method
14.1 INTRODUCTION
Given a square matrix A of order n, if there exists a scalar  (real or complex) and a non-zero
column matrix X such that AX = X, then  is called an Eigen value of A and X is called an Eigen
vector of A corresponding to an Eigen value .
AX = X
=  I X where I is the unit matrix of the same order as that of A.
 AX  IX = O, where is the null matrix
 (A  I)X = ).
This is a homogeneous system of n equations with n unknowns of X. A non-trivial solution exists
only when the coefficient determinant | A   I | = 0.
Objective
At the end of this unit the students should be able to know:-
1. To find the eigen values and Eigen vectors using power method
2. Learn the Jacobi’s method for symmetric matrix
3. Learn Given’s method
14.3 PROPERTIES OF EIGEN VALUES
1. The sum of eigen values of a matrix A is equal to the sum of its principal diagonal elements.
2. The diagonal elements of a triangular matrix are the eigen values of the matrix.
3. The matrix B = P-1AP and A have the same eigen values.
4. The matrix A and A have the same eigen value but different eigen vectors.
5. If 1, 2,…, n are the Eigen values of a matrix A, then

(i) Am has eigen values , where m is positive integer.

(ii) A-1 has eigen values .


6. The product of eigen values of a matrix A is equal to value of its determinant.
7. The eigen values of a symmetric matrix are all real.
8. The eigen values of a Hermitian matrix are all real.
9. The eigen values of a Skew-Hermitian matrix are either zero or purely imaginary.
10. If  is the eigen value of the matrix A and X is the corresponding eigen vector, then kX (k being a
scalar) is also the eigen vector corresponding to .
Remarks 11. Among all the eigen values of a matrix, the one which is largest in magnitude is called the
dominant eigen value or dominant root.

12. If  is an eigen value of an orthogonal matrix then is also its eigen value.
Eigen Value Problems 199

Example 1 : Find the eigen values and corresponding eigen vectors of the matrix

A=
Solution : The characteristic equation of A is | A   I | = 0

i.e, =0
or 3  182 + 45 = 0
or (  3) (  15) = 0   = 0, 3, 15
Hence, eigen values of A are 0, 3, 15.
14.4 TO FIND EIGEN VECTORS
The eigen vectors corresponding to an eigen value is a non-zero solution of (A   I)X = 0,
where X is a column vector

i.e., =0 (1)
Corresponding to  = 0, the eigen vectors are given by

(A  0I)X = O or =O (2)
 8x1  6x1 + 2x3 = 0
6x1 + 7x2  4x3 = 0
2x1  4x2 + 3x3 = 0
These equations determine a single linearly independent solution. From first two equations, we
have

or
giving the eigen vector (1, 2, 2), so that every non-zero multiple of this vector is an eigen vector
corresponding to  = 0.
Corresponding to  = 3, the eigen vectors are given by

(A  3I)X = O or
 5x1  6x1 + 2x3 = 0
6x1 + 4x2  4x3 = 0 Remarks
2x1  4x2 + 0x3 = 0
From first two equations, we have
200 Programming in C and Numerical Analysis

or
giving the eigen vector (2, 1, 2), so that every non-zero multiple of this vector is an eigen vector
corresponding to  = 3.
Corresponding to  = 15, the eigen vectors are given by

(A  15I)X = O or
 7x1  6x1 + 2x3 = 0
6x1  8x2  4x3 = 0
2x1  4x2  12x3 = 0
From first two equations, we have

or
giving the eigen vector (2,2, 1), so that every non-zero multiple of this vector is an eigen vector
corresponding to  = 15.
Hence the three eigen vectors are (1, 2, 2), (2, 1, 2), (2, 2, 1).
14.5 POWER METHOD
Method : (To find the largest eigen value and the corresponding eigen vector). Suppose A is the
given square matrix.
Step 1 : Choose the initial vector such that the largest element is unity.
(choose initially an eigen vector X(0) = (1, 0, 0).
Step 2 : This normalized (taking the largest component out as a common factor) vector X (0) is pre-
multiplied by the given matrix.
(evaluate the matrix product AX(0) which is written as (1) X(1) after normalization).
Step 3 : This gives the first approximation (1) to be eigen value and X(1) to the eigen vector.
Step 4 : Compute AX(1) and again put in the form AX(1) = (2) X(2) by normalization which gives the
second approximation. Similarly we evaluate AX(2) and put it in the form AX(2) = (3) X(3).
Step 5 : Repeat this process till difference between two successive iterations is negligible. The values
so obtained are respectively the largest eigen value and the corresponding eigen vector of the given
square matrix A.
Example 1 : (i) Find the largest eigen value and the corresponding eigen vector of the matrix

A=
(ii) Also find smallest value of A and corresponding eigen vector.
(iii) Find all the eigen values of A.
Eigen Value Problems 201

Remarks

Solution : (i) Let the initial eigen vector be X(0) = . Then

AX(0) =
 The first approximation to the eigen value is 1 and the corresponding eigen vector is

X(1) =

Now AX(1) =

 (2) = 7, X(2) =

AX(2) =

 (3) = 3.4 and X(3) =

Similarly, AX(3) =

AX(4) =

AX(5) =
We observe that X(6) = X(5)
202 Programming in C and Numerical Analysis

Remarks

Hence, the largest eigen value is 4 and the corresponding eigen vector is .

(ii) Consider B = A  4I =

=
Now we shall find the largest eigen root of B.

Starting with X(0) = , we have the following iterations :

BX(0) =

(1) = 3, X(1) =

BX(1) =

(2) = 4.98, X(2) =


We observe that X(2) = X(1)
 The largest eigen value of B is 4.98 i.e., 5 approximately and the corresponding eigen vector is

.
Hence the smallest eigen value of A=largest eigen value of B+largest eigen value of A
=  5 + 4 = 1.
(iii) Since, sum of all diagonal elements of matrix A = sum of all eigen values of matrix A
1 + 2 + 3 = 4 + (1) + 3  3 = 3
Limitation of Power Method
Eigen Value Problems 203

This method only used to determine the largest eigen value.


Now we discuss a new method (for symmetric matrix) to obtain all eigen values. This is named as
Jacobi’s method for symmetric matrix.
14.6 JACOBI’S METHOD FOR SYMMETRIC MATRIX
Remarks Jacobi’s method is based on the fact that if a matrix B is orthogonal, i.e., if BB T = I, then the eigen
values of BABT are the same as those of A. A sims second-order orthogonal matrix is given by

B= (1)

Another example is B = (2)


The matrices, as B in (2) are known as rotation matrices, the rotation in (2) being in (2,3) plane.
Jacobi’s method consists in obtaining rotation matrices B1, B2, B3,..,Br that their product B satisfies the
equation
B-1AB or BABT = D, where D is a diagonal metrix.
From equation (2) we can easily generalize : if B is an n  n orthogonal matrix, then a rotation in
the (p, q) plane, we have

except that

To see the form of BABT, we consider the second-order symmetric matrix A given by

A= (3)
Let us take B of the form given in (1) so that

BABT =

(4)

So, we see that the matrix BABT is a symmetric matrix and its (1,2) elements is given by

Similarly, for an (n  n) matrix B, the (p, q) element of BABT is given by

(5)
T
For BAB to be a diagonal matrix, we must have the (p, q) element equal to zero.
Remarks

i.e.,
204 Programming in C and Numerical Analysis

 (6)
This equation gives four values of , but to get the least possible rotation, we choose

. From (6) we get

= (7)

If app  aqq, If app = aqq, then (8)


Let B1, B2, …, Br be the rotation matrices used respectively in annihilating the off-diagonal
elements. Then we have

BrBr-1….B2B1A (9)
Since the product of orthogonal matrices is also an orthogonal matrix, it is obvious that D is a
diagonal matrix-with the eigen values of A on the diagonal.
For finding the eigen vectors of A, we assume

(10)
Then (9) gives
PTAP = D
 AP = (PT)-1D = PD
Which shows that the columns as P are the eigen vectors of A.
Example 1 : Using Jacobi’s method compute all the eigen value and the corresponding eigen vectors

of the matrix .

Solution : Here A =
The largest off diagonal element is a13 = a31 = 2 and a11 = a33. To annihilate the (1, 3) element,
we observe that p = 1, q = 3.

We know that

i.e.,
Eigen Value Problems 205

which means
Remarks

Now rotation matrix B1 =

We now obtain

Again, the largest off-diagonal element is a23 = a32 = 2 and a22 = a33. To annihilate the (2, 3)
element we observe that p = 2, q = 3.

i.e.

which means

Now rotation matrix


206 Programming in C and Numerical Analysis

We now obtain
Remarks

Eigen values are 1, 1 and 5.

For finding the eigen vectors of A, find

i.e.,
Now the eigen vectors of A are the columns of P.

i.e., for eigen value 1 the eigen vectors are

for eigen value 1 the eigen vectors are

for eigen value 5 the eigen vectors are


14.7 GIVEN’S METHOD
A disadvantage of Jacobi’s method is that the elements which were annihilated by a plane rotation
may not remain zero during subsequent rotations. Givens proposed an algorithm using plane rotations,
which preserves the zeros in the off diagonal elements, once they are created. As seen earlier, the
Jacobi’s method leads to a diagonal matrix but the Givens method leads to a tridiagonal matrix and
the eigen values and eigen vectors of the original matrix have to be extracted from those of the
tridiagonal matrix. This will be explained after Householder’s method.
For introducing the method, let us consider the third-order real symmetric matrix given by
Eigen Value Problems 207

(1)
and the orthogonal rotation matrix, B1 in the plane (2, 3) as

(2)

Now, let us compute


Remarks

i.e.,

The (1, 3) element of is a12sin + a13cos.


It will be zero, if a12sin + a13cos = 0  a12sin = a13cos

 (3)
Thus with this value of , the above transformation gives zeros in (1, 3) and (3, 1) positions. Then
we perform rotations in the plane (2, 4) and put (1, 4) = (4, 1) = 0. This would not affect zeros that
have been obtained earlier. Proceeding in this manner, we put (1, 5) = (5, 1) = 0 etc. by performing
rotations in (2, 5), …, (2, n) planes. Then we pass to the elements (2, 4), (2, 5),…, (2, n) and make
them zero by performing rotations in (3, 4), …, (3, n) planes., Ultimately, we produce the matrix

The number of plane rotations required to make a matrix of order n to its tridiagonal form is (n
 1)(n  2).

As B1 is a orthogonal matrix, therefore,

Example 1 : Transform the matrix A = to tri-diagonal form by Given’s method.


Find the eigen vector corresponding to the largest eigen value from the eigen vectors of the tri-
diagonal matrix.
Solution : Step I : Matrix A has only one non-tri-diagonal element a13 = 2 which is to be placed to
zero.
208 Programming in C and Numerical Analysis

Hence only one rotation is required.


To annihilate a13, we define the orthogonal matrix in the plane [2, 3] as

Here

Remarks

Now,

This is the required tri-diagonal form.


Step II : The characteristic roots of A1 are given by

| A1  I | =
The Sturm sequence {fn} is defined as
f0() = 1
f1() = 1  

= 2  4  5
Eigen Value Problems 209

and f3() = (1)f2()  (0)2.f1()


= (1) (2  4 ) = ( + 1) ( +1) (  5)
Roots of equations f3() = 0 are 1, 1, 5, which are the eigen values of A.
The largest eigen value in magnitude is 5.
Now, eigen vector Y corresponding to eigen value 5 of A1 is a non-zero solution of
[A1  I]Y = 0

i.e.,
Remarks

which gives
y3 = 0
On solving, we get y1, y2 = , y3 = 0

Hence
 Required eigen vector of A = B1Y

14.8 HOUSE-HOLDER’S METHOD


This method is used for tri-diagonalisation of a general symmetric matrix by using elementary
orthogonal transformations instead of plane rotations used in Given’s method. This method has
following advantages :
(i) This method is faster in comparison to Given’s method.
(ii) It reduces entire row/column in a single calculation.
(iii) It requires less storage space.
This method consists of Pre and Post multiplying a real symmetric matrix A by a real symmetric
orthogonal matrix P such that PAP reduces to tri-diagonal form. This reduction is done in exactly (n 
2) transformations, where A is of order n  n and
P = I – 2ww (1)

Where and w = [x1 x2 x3…..xn] in general such that


210 Programming in C and Numerical Analysis

ww = I = ww

 (2)
Now, P = (I  2ww)
= I  2(w)(w) = I  2ww = P
 P is a symmetric matrix
Also, PP = (I( - 2ww)(I  2ww) = (I  2ww)(I  2ww)
= I  4ww + 4wwww = I  4ww + 4wIw
= I  4ww + 4ww = I
 P is an orthogonal matrix.
Hence P is a symmetric orthogonal matrix.
Let us now explain the Hourse Holder’s method by taking a matrix A of order 33 i.e. Remarks

A
 w is of order 3  1 and w is of order 13

P = I  2ww =

Since P is an orthogonal matrix, therefore elements at the position (1, 1) (i.e., first row and first
column) say b11 should be unity
i.e.,  x1 = 0

 P = I  2ww= (3)

where (4)

Now, PAP =

=
Here element at the position (1, 3) (i.e., first row and third column) say b 13
Eigen Value Problems 211

(5)
where q = a12x2 + a13x3 (6)
Now, element at the position (1, 2) (i.e., first row and second column) say b12

(7)
Squaring equations (5) and (7) and adding them, we have

Remarks

Since PAP should be a tri-diagonal matrix


 b13 = 0 (8)

 (9)
 From equations (7) and (9), we have

(10)
Also from equations (5) and (8), we have
a13  2qx3 = 0 (11)
Multiplying equation (10 by x2 and (11) by x3 and adding them, we get


 q  2q =  Sx2 [Using equation (6) and (4)]
 q =  Sx2
Put this value in equation (10), we get
a12 + 2x2(Sx2) = S


From equation (11)

On account of all these operations


212 Programming in C and Numerical Analysis

D = PAP = , which is the required tri-diagonal form.

Example 1 : Transform the matrix A = to tri-diagonal form by House-holder’s method.


Solution : To reduce A to tri-diagonal form, only one transformation is required.
(Here n = 3,  n  2 = 3  2 = 1)
For the first transformation, we choose

The parameters in the transformation are obtained as follows :


Remarks

Also,

Now,
Eigen Value Problems 213

Hence, the required House-holder transformation with A = A1 is


A2 = P2.A1.P2

Remarks

which is the required tri-diagonal form.

14.9 QR METHOD

If we wish to calculate all eigen values of a matrix, then QR method is the most efficient and
general method. But QR method is quite complex in both its theory and application. Here we are
giving only an introduction to the theory of this method.
214 Programming in C and Numerical Analysis

Let A = A1 be the given matrix which has been factorized as A1 = Q1R1, where Q1 is an orthogonal
matrix and R1 is an upper triangular matrix.

Let

Now factorize A2 such that A2 = Q2R2, where Q2 is an orthogonal matrix and R2 is an upper
triangular matrix.

Let

Now factorize A3 such that A3 = Q3R3, where Q3 is an orthogonal matrix and R3 is an upper
triangular matrix.

Continuing like this, we get a sequence of matrices A1, A2, A3,….,Am, Am+1 such that

 The matrix Am+1 is similar to matrix Am. But matrix Am is similar to matrix Am-1.

 Matrix Am+1 is similar to matrix Am-1.

By induction method, we see that matrix Am+1 is similar to matrix A1.


Thus, we get a sequence of matrices <A1, A2,…,Am,…> such that the sequence either converges to
a triangular matrix or near to a triangular matrix. As eigen values of a triangular matrix are its
diagonal elements, so the eigen values of the given matrix can be calculated.
Remarks
14.10 LANCZO’S METHOD
By using the methods devised by Given and Householder, we can reduce real symmetric matrices
to tri-diagonal form. For arbitrary matrices a similar reduction can be performed by a technique
suggested by Lanczo’s. In this method two system of vectors x 1, x2, x3,…,xn and y1, y2,…,yn are
constructed which are biorthogonal

i.e. for i  j (1)

Choose initial vectors x1, y1 such that


The new vectors are formed according to the following rules :
Eigen Value Problems 215

(2)

and (3)
Using biorthogonality conditions, we can determine aij and bij.
For i = 1, 2, 3,…,j, we have

 [Using (2)]
Using biorthogonality condition, we get

If  0, then (4)

Similarly, (5)
For i  j  2, we have

[Using (3)]
=0 [Using (1)] 

=0 when i  j  2
Similarly bij = 0 when i  j  2.
From (2), we have
Remarks
216 Programming in C and Numerical Analysis

(6)
From (3), we have

(7)
If the vectors x1, x2,….,xn are linearly independent and matrix X is formed with x1, x2, xn as
columns and tri-diagonal matrix J is formed from the coefficients a j-1,j and ajj which 1’s in the
remaining diagonal, then

Here AX = XJ i.e., J = X-1AX


Similarly if matrix Y is formed from the vectors y1, y2, …., yn and matrix K is formed from the
coefficients bj-1,bjj, then
K = Y-1AY.

Certain complications may arise. For example it can happen that even if xi  0, yi  0.
In some cases it may happen that some xi or yi vector is zero. The simplest way out is to choose other
initial vectors. Sometimes it is possible to get around the difficulties by modifying the formulae
themselves.
Lanczo’s method can be used with real symmetric or Hermitian matrices by choosing one
sequence of vectors forming an orthogonal system.
Eigen Value Problems 217

Exercise 14.1 Remarks

Question 1 : Find the largest eigen-value and the corresponding eigen vector of the matrices

(i) (ii)

Question 2 : Using Jacobi’s method, find all the eigen values and eigen vectors of the matrices.

(i) (ii)

Question 3 : Using Given’s method, reduce the following matrices to tri-diagonal form

(i) (ii)

Question 4 : using House-holder’s method, reduce the matrix to tri-diagonal form.

Answers 14.1

Question 1 : (i) 11.66, (ii) 4,

Question 2 : (i)

(ii)
218 Programming in C and Numerical Analysis

Remarks

Question 3 : (i) (ii)

Question 4 :

Keywords - Eigen value, Eigen Vector, Power method, Given’s method.

Summary
In this unit , we have study methods for finding Eigen values and eigen vectors. In particular
finding the largest eigen value and corresponding eigen vector.
Remarks
CHAPTER – XV
NUMERICAL SOLUTION OF ORDINARY DIFFERENTIAL
EQUATIONS
15.0 STRUCTURE
15.1 Introduction
15.2 Objective
15.3 Euler’s Method
15.4 Modified Euler’s Method
15.5 Taylor’s Series Method
15.6 Runge-Kutta Method
15.7 Milne-Simpson’s Method
15.8 Boundary Value Problem (BVP)
15.1 INTRODUCTION
Many problems in science and technology can be formulated into differential equations satisfying
certain given conditions. The analytic methods of solving differential equations are applicable only
for limited class of equations so we need numerical methods for their solution.
15.2 OBJECTIVE
At the end of this unit students should be able to know
1. How solve differential equation using various numerical methods.
2. Use of R.K. method of order 2 and 4.
3. Use of Single step and multistep methods.
15.3 EULER’S METHOD
Consider the initial value problem,

with y(x0) = y0
We have Taylor’s series expansion,

Put x = x1 = x0 + h, we get

Approximating Taylor’s expansion up to the first degree term of h only since h2, h3, ... are very small,
we have
y(x1) = y(x0) + hy(x0)
= y(x0) + hf(x0, y0)

(since y(x0) = = f(x0, y0))


or
y1 = y0 + hf(x0, y0)
Similarly, if x2 = x1 + h we can write
y2 = y1 + hf(x1, y1)
In general, if xi+1 = xi + h we have
220 Programming in C and Numerical Analysis

yi+1 = yi + hf(xi, yi) where i = 0, 1, 2, 3, 4,…..


Remarks This is known as Euler’s formula or Euler’s method.
Example 1 : Using Euler’s method, find an approximate value of y corresponding to x = 1, given that

= x + y with initial condition y = 1 at x = 0.

Solution : We have = x + y = f(x, y)


Initially y0 = 1 at x0 = 0. We take n = 10 and h = 0.1.
 x0 = 0, x1 = 0.1, x2 = 0.2, x3 = 0.3, x4 = 0.4, x5 = 0.5, x6 = 0.6, x7 = 0.7,
x8 = 0.8, x9 = 0.9, x10 = 1.0.
The approximate value of y at x1 = 0.1 is given by
y1 = y0 + hf(x0, y0)
= y0 + h(x0 + y0)
= 1 + 0.1 (0 + 1) = 1.1
The approximate value of y at x2 = 0.2 is given by
y2 = y1 + hf(x1, y1)
= y1 + h(x1 + y1)
= 1.1 + 0.1 (0.1 + 1.1) = 1.22
The approximate value of y at x3 = 0.3 is given by
y3 = y2 + hf(x2, y2)
= y2 + h(x2 + y2)
= 1.22 + 0.1 (0.2 + 1.22)
= 1.22 + 0.1(1.42) = 1.36
The approximate value of y at x4 = 0.4 is given by
y4 = y3 + hf(x3, y3)
= y3 + h(x3 + y3)
= 1.36 + 0.1 (0.3 + 1.36)
= 1.36 + 0.1(1.66) = 1.53
The approximate value of y at x5 = 0.5 is given by
y5 = y4 + hf(x4, y4)
= y4 + h(x4 + y4)
= 1.53 + 0.1 (0.4 + 1.53)
= 1.53 + 0.1(1.93) = 1.72
The approximate value of y at x6 = 0.6 is given by
y6 = y5 + hf(x5, y5)
= y5 + h(x5 + y5)
= 1.72 + 0.1 (0.5 + 1.72)
= 1.72 + 0.1(2.22) = 1.94
The approximate value of y at x7 = 0.7 is given by
y7 = y6 + hf(x6, y6)
= y6 + h(x6 + y6)
= 1.94 + 0.1 (0.6 + 1.94)
= 1.94 + 0.1(2.54) = 2.19
The approximate value of y at x8 = 0.8 is given by
y8 = y7 + hf(x7, y7)
= y7 + h(x7 + y7)
= 2.19 + 0.1 (0.7 + 2.19)
Numerical Solution of Ordinary Differential Equations 221

= 2.19 + 0.1(2.89) = 2.48

The approximate value of y at x9 = 0.9 is given by Remarks


y9 = y8 + hf(x8, y8)
= y8 + h(x8 + y8)
= 2.48 + 0.1 (0.8 + 2.48)
= 2.48 + 0.1(3.28) = 2.81
The approximate value of y at x10 = 1 is given by
y10 = y9 + hf(x9, y9)
= y9 + h(x9 + y9)
= 2.81 + 0.1 (0.9 + 2.81)
= 2.81 + 0.1(3.71) = 3.18
Thus at x = 1.0 the required approximate value of y is 3.18.
15.4 MODIFIED EULER’S METHOD
This is a modification of Euler’s method. Instead of f(x 0, y0) in Euler’s method, if we take the
average of f(x, y) at (x0, y0) and (x1, y1) we get the modified Euler’s method as

where y1 is given by y1 = y0 + h f(x0, y0). is the first modified value of y1.

Let be the second approximation to y1


The third approximation to y1 is given by

Thus the (j + 1)th iteration formula for the approximation of y1 is

, j = 0, 1, 2, 3, 4, ….
We repeat this process till two consecutive values of y agree. Let y 1 be the final value obtained to the
desired accuracy. Using this value of y1, we compute y2 using Euler’s method as
y2 = y1 + h f(x1, y1)

Now let

where is the first approximation formula for y2. The second approximation formula for y2 as

We repeat this process until two consecutive values agrees. Then we proceed to calculate y 3 as above
and continue the process till we calculate yn.

Example 1 : Given that and y = 1 and x = 1. Find approximate value of y at x = 1.8 in


four steps of 0.2 each, using Euler’s modified method.

Solution : We have , where y = 1 at x = 1

 f(x, y) =
222 Programming in C and Numerical Analysis

Taking n = 5 and h = 0.2, we have


x0 = 1, x1 = 1.2, x2 = 1.4, x3 = 1.6, x4 = 1.8 and x5 = 2.0.
Also y0 = 1

Remarks

By Euler’s method, we have
y1 = y0 + hf(x0, y0)
= 1 + 02(3) = 1.6


= 2 + 1.3856 = 3.3856
By Euler’s modified method, the approximations to y1 are

= 1 + 0.1 [3 + 3.3856] = 1.6386

= 1 + 0.1[3 + 3.4023] = 1.6402

= 1 + 0.1[3 + 3.4029] = 1.6403

= 1 + 0.1[3 + 3.4030] = 1.6403


Thus we take y1 = 1.6403 and proceed further to find y2.

Now,

= 2 + 1.403 = 3.403
By Euler’s method, we have
y2 = y1 + hf(x1, y1)
= 1.6403 + 0.2(3.403) = 2.3209

= 2 + 1.8026 = 2.8026
By Euler’s modified method, the approximations to y2 are

= 1.6403 + 0.1[3.403 + 3.8026] = 2.3609

= 1.6403 + 0.1[3.403 + 3.818] = 2.3624


Numerical Solution of Ordinary Differential Equations 223

= 1.6403 + 0.1 [3.403 + 3.8186] = 2.3625

= 1.6403 + 0.1[3.403 + 3.8187] = 2.3625

Thus we take y2 = 2.3625 and proceed further to find y3 Remarks

Now,

= 2 + 1.8187
= 3.8187
By Euler’s method, we have
y3 = y2 + hf(x2, y2)
= 2.3625 + 0.2[3.8187] = 3.1262

= 2 + 2.2365
= 4.2365
By Euler’s modified method, the approximations to y3 are

= 2.3625 + 0.1[3.8187 + 4.2365] = 3.1680

= 2.3625 + 0.1[3.8187 + 4.2514] = 3.1695

= 2.3625 + 0.1[3.8187 + 4.2519] = 3.1696

= 2.3625 + 0.1[3.8187 + 4.252] = 3.1696


Thus we take y3 = 3.1696 and we proceed further to find y4

Now,

= 2 + 2.2520
= 4.252
By Euler’s method, we have
y4 = y3 + hf(x3, y3)
= 3.1696 + 0.2(4.252) = 4.020

=
= 2 + 2.690
= 4.69
224 Programming in C and Numerical Analysis

By Euler’s modified method, the approximations to y4 are

= 3.1696 + 0.1[4.252 + 4.69] = 4.0638

Remarks = 3.1696 + 0.1[4.252 + 4.7046] = 4.0653

= 3.1696 + 0.1[4.252 + 4.7051] = 4.0653


Thus we take y4 = 4.0653 and we proceed further to find y5.

Now,

= 2 + 2.7051
= 4.7051
By Euler’s method, we have
y5 = y4 + hf(x4, y4)
= 4.0653 + 0.2(4.7051) = 5.0063

=
= 2 + 3.1643
= 5.1643
15.5 TAYLOR’S SERIES METHOD

Consider the first order equation = f(x, y), where y = y0 at x = x0 (1)


Let y = F(x) be the solution of the above equation such that F(x 0)  0. Expanding y = F[x0 + (x –
x0)] by Taylor’s series about point x0, we get

or (2)
This gives the value of y for every value of x for which equation (2) converges.
Putting x = x1 = x0 + h and y = y1 in (2), we get

Similarly, we can obtain


Numerical Solution of Ordinary Differential Equations 225

Where denotes the rth derivative of y w.r.t. x at the point (xm, ym).

Putting the values of we can find ym+1 which is the folution of (1) numerically.
Note : This method works well as long as the successive derivatives can be calculated easily. If the
calculation of higher order derivatives become tedious, then Taylor’s method is not useful.
This is the main drawback of this method and is not of much importance. However, it is
useful for finding starting values for the application of methods like Runge-Kutta method and
Milne Simpson’s method.
Remarks
15.6 RUNGE-KUTTA METHOD
The Taylor’s series method for solving differential equations numerically involves lot of labour in
finding out the higher order derivatives. In Runge-Kutta method, the calculations of higher order
derivatives is not required. Also this method gives greater accuracy. The method requires the
functional values at some selected points and agrees with the Taylor’s series solution up to the term
containing hr, where r differs from method to method and is called the order of that method. In these
methods the accuracy increases at the cost of calculations. The most widely used method is Runge-
Kutta of fourth order.
(i) R-K Method of First Order :
Consider the differential equation

where y = y0 at x = x0. (1)


By Euler’s method, we have

Also we have y1 = y(x0 + h) and on expanding by Tayloy’s series, we have

It shows that Euler’s method agrees with the Taylor’s series method upto the term containing h.
Hence, Euler’s method is the Runge-Kutta method of the first order.
(ii) R-K Method of Second Order :
Using Euler’s modified method, we have

(2)
Putting y1 = y0 + hf(x0, y0) in the right hand side, we get

(3)
where f0 = f(x0, y0).
Expanding by Taylor’s series for a function of two variables, we get
226 Programming in C and Numerical Analysis

 (4)
Also y1 = y(x0 + h)
 Expanding by Taylor’s series, we get

S (5)
Comparing (4) and (5), we get that the Euler’s modified method agrees with the Taylor’s series
solution up to the terms containing h2.
Remarks Thus we can say that the Euler’s modified method is nothing but R-K method of the second order.
The second order R-K method is

where k1 = hf(x0, y0) and k2 = hf(x0 h, y0 + k1)


(iii) R-K Method of Fourth Order (or Simply Runge Kutta Method) :
This method is most commonly used and is often referred to as Runge-Kutta method only. To find

the increment k of y corresponding to an increment h in x by R-K method from = f(x, y), y(x0) =
y0; we proceed as follows :

Calculate k1 = hf(x0, y0),

k4 = hf[x0 + h, y0 + k3]

and
After obtaining values of k1, k2, k3, k4 and k finally compute
y1 = y0 + k

y1 = y0 +
Example 1 : Apply Runge-Kutta fourth order method to find an approximate value of y when x = 0.2

given that = x + y and y = 1 when x = 0.

Solution : Here = x + y = f(x, y)


x0 = 0, y0 = 1 and take h = 0.1
k1 = h  f(x0, y0) = 0.1  f(0, 1) = 0.1  1 = 0.1
Numerical Solution of Ordinary Differential Equations 227

k4 = h  f(x0 + h, y0 + k3) = 0.1  f(0 + 0.1, 1 + 0.1105)


= 0.1 f(0.1, 1.1105) = 0.1  1.2105 = 0.1211


= 0.1104
y1 = y0 + k = 1 + 0.1104 = 1.1104
x1 = x0 + h = 0 + 0.1 = 0.1 Remarks
k1 = h  f(x1, y1) = 0.1  f(0.1, 1.1104)
= 0.1  1.2104 = 0.1210

= 0.1  f(0.15, 1.1709) = 0.1321

k4 = h f(x1 + h, y1 + k3) = h  f(0.2, 1.1104 + 0.1326) = 0.1443


k = 0.1325
y2 = y1 + k = 1.2429
Hence the value of y at x = 0.2 is 1.2429.

Example 2 : Solve = x + y; y(1) = 0 numerically upto x = 1.2 with h = 0.1.


Solution : Here x0 = 1, y0 = 0. Also we have
y= x + y, y = 1 + y, y = y, yiv = y, yv = yiv.
By use Taylor Series

From above
Putting these values

= 0.11033847 = 0.110 (Approximately)


228 Programming in C and Numerical Analysis

Also x1 = 1 + 0.1 = 1.1.


Again by use of Taylor series

But

Hence
= 0.232 (Approx)

Remarks 15.7 MILNE-SIMPSON’S METHOD

Given = f(x, y) and y = y 0 at x = x0. To find an approximate value of y for x = x 0 + nh by


Milne-Simpson’s method.

The given differential equation is = f(x, y)


The initial conditions are y = y0 at x = x0.
In this method, we first obtain the approximate value of y n+1 by predictor formula and then
improve this value by means of corrector formula.
By Newton’s formula for forward interpolation, we have

Where i.e., x = x0 + uh
In terms of y and u, the formula is

(1)
Integrating over the interval x0 to x0 + 4h or u = 0 to 4, we have
Numerical Solution of Ordinary Differential Equations 229

or

Substituting   (E  1), we get

Remarks


This is Milne’s predictor formula.
To obtain the corrector formula, we integrate (1) over the interval x 0 to x0 + 2h or u = 0 to 2. Thus
we have

Substituting   (E  1), we get


230 Programming in C and Numerical Analysis

 (3)
This Milne’s corrector formula.
Since x0, x1, x2, x3, x4 are any five consecutive values of x, so in general equations (2) and (3) can
be written as

(4)

and (5)
Thus Milne-Simpson’s method uses the formulae
xi+1 = xi + h

and the predictor

and the corrector for i = l,4,5,..,(m-1)

Remarks
as an approximation solution to the differential equation .

Example 1 : Apply Milne’s method, to find a solution of the differential equation y = x – y2 in the
range 0  x  for the boundary condition y = 0 at x = 0, when it is given that
x: 0.2 0.4 0.6
y: 0.020 0.0795 0.1762

Solution : Here = f(x, y) x = 0, y = 0


x =0 y0 = 0 f0 = 0
x1 = 0.2 y1 = 0.020 f1 = 0.1996
x2 = 0.4 y2 = 0.795 f2 = 0.3937
x3 = 0.6 y3 = 0.1762 f3 = 0.5689
Numerical Solution of Ordinary Differential Equations 231

Using the predictor


Here x = 0.8 y4 = 0.3049 (1)
f4 = 0.7072
Again using corrector we get y4 = 0.3046 which is same as in equation (1)
Again using predictor

Here x=1 y5 = 0.4554 f5 =0.7926


Now using the corrector

y5 = 0.4555 (2)
f5 = 0.7925
Again using the corrector
y5 = 0.4555 which is same as equation (2)
 y(0.8) = 0.3046, y(1) = 0.4555.

15.8 BOUNDARY VALUE PROBLEM (BVP)


Consider a second order BVP.
p(x) y(x) + q(x) y(x) + r(x) y(x) = f(x)
with boundary conditions : y(x0) = y0, y(xn) = yn (1)
Divide [x0, xn] into ‘n’ subintervals each of length Remarks

Let xi = x0 + ih, i = 0, 1, 2,…,n


By Taylors series expansion :
yi+1 = y(xi+1) = y(x0 + (i + 1)h) = y(x0 + ih + h)

Therefore (2)
Similarly, yi-1 = y(xi  h)
232 Programming in C and Numerical Analysis

(3)
(2)  (3) gives :

Therefore, (4)
Error = O(h2) (higher order of h neglected)
Adding (2) and (3) :

Therefore, (5)
2
Error = o(h )
In finite difference method y and y are replaced by the finite difference using (4) and (5).

Example 1 : Solve the BVP using finite difference


xy + y = 0
y(1) = 1, y(2) = 2
(i) with h = 0.5 and (ii) h = 0.25
Solution : (i) Consider h = 0.5; x0 = 1, x1 = 1.5, x2 = 2

y0 = y(x0) = y(1) = 1
Remarks y1 = y(x1) = y(x0 + 1.h) = y(1+0.5) = y(1.5) = ?
y2 y(x2) = y(2) = 2.
Replacing y by the finite difference :

(1)
Take i = 1, we get
Numerical Solution of Ordinary Differential Equations 233


 4.5 – 3y1 + 0.25y1 = 0
 2.75y1 = 4.5


Therefore y1 = y(1.5) = 1.6364
(ii) Consider h = 0.25

; x0 = 1, x1 = 1, x2 = 1.5, x3 = 1.75, x4 = 2
y0 = y(x0) = y(1) = 1
y1 = y(x1) = y(1.25) = ?
y2 = y(x2) = y(1.5) = ?
y3 = y(x3) = y(1.75) = ?
y4 = y(x4) = y(2) = 2
Put i = 1, 2, 3 in equation (1)
That is, xi[yi+1  2yi + yi-1] + yih2 = 0

Put i = 1, x1[y2  2y1 + y0] + y1 =0

Therefore 1.25[y2  2y1 + 1] + y1 =0


 16  1.25 (y2  2y1 + 1) + y1 = 0
 20 (y2  2y1 + 1) + y1 = 0
 20y2  39y1 + 20 = 0 (2) Remarks

Putting i = 2, we get
24y3  47y2 + 24y1 = 0 (3)
Put i = 3, we get
234 Programming in C and Numerical Analysis

56 – 55y3 + 28y2 = 0 (4)


Therefore we have to solve the system
39y1 – 20y2 + 0.y3 = 20
24y1  47y2 + 24y3 = 0
0.y1 – 28y2 + 55y3 = 56
We get y1 = 1.3513, y2 = 1.6349, y3 = 1.8508

Example 2 : Solve y + xy  2y = 0 (1)


with y(1) = y(1), y(2) = 5, h = 0.5
Solution : x0 = 1, x1 = 1.5, x2 = 2
y0 = y(x0) = y(1) = y(1) = y(x0) = y0 = ?
y1 = y(x1) = y(1.5) = ?
y2 = y(x2) = y(2) = 5.

Substituting in (1) we get

Where and

 4(yi+1  2yi + yi-1) + xi(yi+1  yi-1)  2yi = 0 (2)


Put i = 0 in (2)
4(y1  2y0 + y-1) + x0(y1  y-1)  2y0 = 0 (3)

Now


Therefore (3) becomes,
4(y1  2y0 + y1  y0) + x0(y1  y1 + y0)  2y0 = 0
Therefore 8y1  13y0 = 0 (4)
Put i = 1, 10y1 + 2.5y0 = 27.5 (5)
y1 = 3.25 , y0 = 2

Exercise  15.1
Remarks
Numerical Solution of Ordinary Differential Equations 235

Question 1 : Using Euler’s method, find an approximate value of y corresponding to x = 1 given


= x + y, and y(0) = 1

Question 2 : Solve the following by Euler’s Modified method = log(x + y) , y(0) = 2 at x = 1.2
and 1.4 with h = 0.2
Question 3 : Apply Runge-Kutta 4th order method to find an approximate value of y when x = 0.2

given that = x + y and y = 1 when x = 0


Question 4 : Use Taylor’s series method to find at x = 0.01 (upto 5th derivative term) given that

= x – y2 with y(0) = 1

Question 5 : Using Runge-Kutta method of order 4, find y for x = 0.1, 0.2, 0.3 given that = xy +
y2, y(0) = 1 continue the solution at x = 0.4 using Milne’s method.
Question 6 : Solve the B.V.P.
xy + y = 0, y(1) = 1, y(2) = 2, y(1.25) = 1.3513, y(1.5) = 1.635, y(1.75) = 1.8505

Answers  15.1

1. 3.18 2. 2.5351, 2.6531 3. 1.2429 4. 0.9138


5. 1.1169, 1.2774, 1.5042, 1.8392
Keywords : First order and first degree differential equations Euler’s method, Taylor series method,
Runge-Kutta method.
Summary : In this unit, we considered various methods of numerical solution of first order and first
degree differential equations. They include Taylor series method, Euler’s method, Runge-Kutta
method.
Remarks

CHAPTER – XVI
APPROXIMATION
16.0 STRUCTURE
16.1 Introduction
16.2 Objective
16.3 Principle of Least Squares
16.4 Fitting of a Straight Line
16.5 Fitting of Second Degree Parabolic Curve
16.6 Fitting of an Exponential Curve of the Type y = aebx
16.7 Fitting of the Curve y = abx
16.8 Fitting of the Logarithmic Curve of the Form y = axb
16.9 Some Chebyshev Polynomials
16.1 INTRODUCTION
The approximations can be made in terms of polynomial equations, exponential functions etc.
These functions contain certain unknown constants which are to be determined with the help of given
set of observations. The procedure of evaluating the unknown constants with the help of given data is
known as curve fitting.
In this chapter, the most frequently used method to obtain the closest fit to the given data
containing various errors of measurements has been discussed. The method is known as ‘Least Square
Method’.
16.2 Objective : At the end of this unit the student should be able to :
1. Learn the linear law to fit a numerical data
2. Learn various methods of curve fitting.
3 Analyze the advantages of different methods
16.3 PRINCIPLE OF LEAST SQUARES
Let (X1, Y1), (X2, Y2),…,(Xn,Yn) be the given set of observations and suppose we want to fit a
function of the form
Y = f(X). (8.1)
The theoretical values of Y can be obtained by putting X = X i, i = 1, …,n, in (8.1). Let these
denoted by f(X1), f(X2),…f(Xn). Now f(Xi), i = 1,….,n, may not be equal to Y i. The theoretical and
observed values of Y for given X are shown in the Table 8.1.
Table 8.1
X Observed Y Theoretical Y
X1 Y1 f(x1)
X2 Y2 f(X2)
X3 Y3 f(X3)
: : :
Xn Yn f(Xn)

The graph of the observations given in table 8.1 is shown in Fig. 8.1. The points Y i will lie above
or below the points f(Xi) on the curve Y = f(X) depending whether
Yi > f(Xi) or Yi < f(Xi) for i = 1, 2,…., n
Approximation 237
Remarks
yn
*
Y :
:
y=f(x) *
f(xn)
y1 * *f(x2)
: :
: :
* y2
*
f(x1)

o
x1 x2 xn X
Fig. 8.1
The differences in the values of Yi  f(Xi) gives an indication about the degree of representation
the function Y = f(X) have with the given set of observations. Now any function for which the sum of
these differences i.e. Yi  f(Xi) for all observations is minimum or least can be considered to be the
best fit i.e.
This implies that to get the curve of the best fit the sum of the differences Y i  f(Xi), i = 1,..,n
should be minimized. But these differences will be positive for some values of i and negative for other
values of i so that the sum of all these differences may sometimes be equal to zero. Thus to have a
clear idea of the magnitude of deviations between the observed and the theoretical values we consider
the sum of the squares of differences between Yi and f(Xi) i.e. to get the curve of the best fit,

(8.2)
is minimized. Since we are minimizing the sum of the squares of deviations, the method is known as
least squares method. The fitting of the relation (….) implies, determination of the constants or
coefficients of (8.1) for the given data such that (8.2) is minimum. This is done by applying the theory
of maxima and minima i.e. differentiating (8.2) w.r.t. the unknown constants of the function y = f(x)
and putting these equal to zero. If there are k constants, then we shall have k equations. The equations
can be solved by the methods described in chapter …. To get the values of k unknown constant. These
equations are known as Normal Equations.
The procedure for getting these normal equations and the corresponding solution will depend
upon the nature of the function y = (x). In remaining sections of this chapter, methods for fitting
different forms of the function y = (x) to the given data by least squares method have been explained.

16.4 FITTING OF A STRAIGHT LINE


In this case p = 1, so that curve y = a0 + a1x is to be fitted to the given data (xi, yi), (i = 1, 2,….,n).
Put x = xi in y = a0 + a1x; then the theoretical or fitted values is given by the residue or error

or di = yi – a0  a1xi, i = 1, 2,…,n

Let
238 Programming in C and Numerical Analysis

Here the principle of least squares described in section 12.3 is now applied to determine the line Remarks
of best fit, i.e., a0 and a1 are determined in such a way that S is minimum. Using (4), we get the
normal equations as

and

or (1)

and (2)
Solving these two normal equations, we can obtain a0 and a1.
Example 1 : Fit a straight line to the following data :

x: 1 2 3 4 5 8
y: 2.4 3 3.6 4 5 6
Solution : Let the straight line to be fitted to the data be y = a + bx; then the normal equations are y
= na + bx, xy = ax + bx2

x y x2 xy
1 2.4 1 2.4
2 3 4 6.0
3 3.6 9 10.8
4 4 16 16.0
6 5 36 30.0
8 6 63 48.0
24 24 130 113.2

Here, n = 6, x = 24, y = 24, xy = 130 and x2 = 113.2


On substituting these values the normal equations become
24 = 6a + 24b (1)
and 113.2 = 24a + 130b (2)
Solving (1) and (2), we get a = 1.976 and b = 0.506
Hence, the required line is y = 1.976 + 0.506x.
Example 2 : Using the method of least square fit a straight line to the following data:

x: 1 2 3 4 5
y: 2 4 6 8 10

Solution : Let the straight line to be fitted to the data be


y = a + bx (1)
Then the normal equation are
y = an + bx (2)
and xy = ax + bx2
Approximation 239

The table is given below :

Remarks x y xy x2
1 2 2 1
2 4 8 4
3 6 18 9
4 8 32 16
5 10 50 25
x=15 y=30 xy=110 x2=55

Here, n = 5, x = 15, y = 30, xy = 110, x2 = 55 substituting these values in (2) and (3), we get
30 = 5a + 15b
and 110 = 15a + 55b
Solving these equations, we get a =0, b = 2.
Hence, the required line is y = 0 + 2x i.e. y = 2x

16.5 FITTING OF SECOND DEGREE PARABOLIC CURVE


Let the second degree parabolic curve to be fitted to the given data (x i, yi), (i = 1, 2, 3,
…,n) be
y = a + bx + cx2 (1)
putting x = xi, we get

yi = a + bxi +

then, (2)
Using the method of least square, we get the following normal equations :

i.e., (3)

i.e., (4)

i.e., (5)
Solving these normal equations we can obtain the best value of a, b and c.
Example 1 : Fit a second degree parabola to the following data :
x: 1.0 1.5 2.0 2.5 3.0 3.5 4.0
y: 1.1 1.3 1.6 2.0 2.7 3.4 4.1
Solution : Here the number of data n is odd, so we take the origin for x series at the middle value 2.5.
240 Programming in C and Numerical Analysis

Now, let us put


Remarks

= 2x – 5 (1)
So that the curve to be fitted is
y = a + bX + cX2 (2)
The table is given below :
x y X X2 X3 X4 XY X2y
1.0 1.1 3 9 27 81 3.3 9.9
1.5 1.3 2 4 8 16 2.6 5.2
2.0 1.6 1 1 1 1 1.6 1.6
2.5 2.0 0 0 0 0 0.0 0.0
3.0 2.7 1 1 1 1 2.7 2.7
3.5 3.4 2 4 8 16 6.8 13.6
4.0 4.1 3 9 27 81 12.3 36.9
16.2 0 28 0 196 14.3 69.9

The normal equations are


y = an + bX + cX2 (3)
Xy = aX + bX2 + cX3 (4)
X2y = ax2 + bX3 = cX4 (5)
From the table we have, n = 7, y = 16.2, X = 0, X = 28, X = 0, X4 = 196, Xy = 14.3, X2y =
2 3

69.9, substituting these values in (3), (4) and (5), we get


16.2 = 7a + 28c
14.3 = 28b
69.9 = 28a + 196c
Solving these equations, we get a = 2.07, b = 0.511, c = 0.061
 y = 2.07 + 0.511X + 0.061X2
Now replacing X by 2x5 in above equations, we get
y = 2.07 + 0.511(2x  5) + 0.061(2x  5)2
= 1.04  0.198x + 0.244x2
This is the required parabola of best fit.
Example 2 : Fit a second degree parabola from the following data :
x: 0.0 1.0 2.0 3.0 4.0
y: 1.0 4.0 10.0 17.0 30.0
Solution : Let the second degree parabola to be fitted to the given data be
y = a + bx + cx2 (1)
The normal equations are
y = an + bx + cx2 (2)
xy = ax + bx + cx
2 3
(3)
x2y = ax2 + bx3 = cx4 (4)
The table is given below :
x y xy x2 x2y x3 x4
0 1 0 0 0 0 0
1 4 4 1 4 1 1
2 10 20 4 40 8 16
3 17 51 9 153 27 81
Approximation 241

4 30 120 16 480 64 256


10 62 195 30 677 100 354
Remarks
Here n = 5, x = 10, y = 62, xy = 195, x2 = 30, x2y = 677, x3 = 100, x4 = 354,
substituting these values in (2), (3) and (4), we get
62 = 5a + 10b + 30c
195 = 10a + 30b + 100c
677 = 30a + 100b + 354c
Solving these equations, we get a = 1.2, b = 1.1 and c = 1.5
Hence, the required second degree parabola of best fit is
y = 1.2 + 1.1x + 1.5x2.
16.6 FITTING OF AN EXPONENTIAL CURVE OF THE TYPE y = aebx
First of all reduce the curve y = ae bx to a linear form by using some simple transformation. Taking
logarithm on both the sides, we get
Logmy = logma + bx logme.
Put logmy = Y, logma = A and blogme = B, then above equation becomes
Y = A + Bx (1)
The normal equations for (1) are
Y = An + Bx (2)
xY = Ax + Bx2 (3)
Solving these equations, we get A and B and from these, we can find a and b as discussed in two
cases :
Case I : When m = e, then A = loge a  a = eA
and B = b loge e = b
Case II : When m = 10, then
A = log10 a  a = 10A
and B = log10 e = (0.43429)b.
Example 1 : Fit the curve Y = aebX to the following data :
X: 1 2 3 4 5 6 7 8
Y: 15.3 20.5 27.4 36.6 49.1 65.6 87.8 117.6
Solution : Taking logarithm of both the sides, we get
Log Y = log a + bX log10 e.
Putting log Y = y, log a = A and b log10 e = B, we get
y = A + BX.
The equation is linear in y and X and can be easily fitted to the given data. The calculations are
shown in table given below :

X X4=x Y y = log Y xy x2
1 3 15.3 1.1847 3.5541 9
2 2 20.5 1.3118 2.6236 4
3 1 27.4 1.4378 1.4378 1
4 0 36.6 1.5635 0 0
5 1 49. 1.6911 1.6911 1
6 2 65.6 1.8169 3.6338 4
7 3 87.8 1.9435 5.8305 9
8 4 117.6 2.0704 8.2816 16
x = 4 12.9107 11.825 44
242 Programming in C and Numerical Analysis

Using the normal equations, we get Remarks


12.9107 = 8A + AB where A = A  4B
11.8215 = 4A + 44B
Solving for A and B, we get
A = 1.5548 i.e. A = 1.0768
and B = 0.1205
 a = Anti log 1.0768 = 12.50

Hence the fitted curve is Y = (12.50) e0.28X

16.7 FITTING OF THE CURVE y = abx


First of all reduce the curve y = abx to a linear form, by taking logarithm of both sides, we get
log y = log a + x log b
Let us put log y = Y, log a = A and log b = B, we have
Y = A + xB (1)
The normal equations of (1) are
Y = An + Bx (2)
xY = Ax + Bx2 (3)
Solving the equations, we get A and B and then
a = antilog (A), b = antilog (B).
Example 1 : Using method of least squares, fit a relation of the form y = abx to the following data :
x: 2 3 4 5 6
y: 144 172.8 207.4 248.8 298.5
Solution : The curve of the form y = abx is to be fitted. Then we have
Y = A + Bx (1)
where Y = log10y, A = log10 a and B = log10 b
The normal equations for (1) are
Y = nA + Bx (2)
xY = Ax + Bx 2
(3)

The table is given below


x y Y = log10y xY x2
2 144 2.15836 4.31672 4
3 172.8 2.23754 6.71262 9
4 207.4 2.31681 9.26724 16
5 248.8 2.39585 11.97925 25
6 298.5 2.47494 14.84964 36
20 1071.5 11.5835 47.12547 90
Here, n = 5, Y = 11.5835, xY = 47.12547, x2 = 90
Substituting these values in (2) and (3), we get
11.5835 = 5A + 20B (4)
47.12547 = 20A + 90B (5)
Solving (4) and (5), we get A = 2.00011, B = 0.079147
since a = 10A and b = 10B
 a = 102.00011 = 100.02533
and b = 100.79147 = 6.18686
Approximation 243

Hence, the required curve of best fit is


y = 100.02533x6.18686
Remarks
16.8 FITTING OF THE LOGARITHMIC CURVE OF THE FORM y = axb
First of all reduce the curve y = axb to linear form by laking logarithm of both the sides, we get
log y = log a + b log x
Let us put log y = Y, log a = A and log x = X, then we have
Y = A + bX (1)
The normal equation for (1) are
Y = An + bX (2)
XY = AX + bX2 (3)
Solving these equations, we get A and b, and then
A = antilog(A)

Example 1 : Fit a least square geometric curve y = axb to the following data :
x: 1 2 3 4 5
y: 0.5 2 4.5 8 12.5

Solution : The curve of the type y = axb is to be fitted. Then we have


Y = A + bX (1)
where Y = log10Y, A = log10 a and X = log10 x.
The normal equation for (1) are
Y = nA + bX (2)
and XY = AX + bX2 (3)
The table is given below
x y X=log10x Y=log10y XY X2
1 0.5 0 0.30103 0 0
2 2 0.30103 0.30103 0.09062 0.09062
3 4.5 0.47712 0.65321 0.31166 0.22764
4 8 0.60206 0.90309 0.54371 0.36248
5 12.5 0.69897 1.09691 0.76671 0.48856
15 27.5 2.07918 2.65321 1.7127 1.1693

Here, n = 5, X = 2.07918, Y = 2.65321, XY = 1.7127, X2 = 1.1693


Substituting these values in (2) and (3), we get
2.65321 = 5A + 2.07918b (4)
1.7127 = 2.07918A + 1.693b (5)
Solving (4) and (5), we get A = 3.70764, b = 0.73563.
Since a = 10A so that a = 103.70764 = 5100.82002
Hence, the required curve of best fit is y = 5100.82002x0.73563.

16.9 SOME CHEBYSHEV POLYNOMIALS


Since we have Tn(x) = cos (n cos-1x)
T0(x) = 1, T1(x) = x. (1)
By recurrence relation, Tn+1(x) = 2nTn(x) + Tn-1(x)
Putting n = 1, 2, 3, 4, 5 successively and using (1), we get the first six Chebyshev polynomials
T0(x) = 1
T1(x) = x
T2(x) = 2x2  1
T3(x) = 4x3  3x
244 Programming in C and Numerical Analysis

T4(x) = 8x4  8x2 + 1


T5(x) = 16x5  20x3 + 5x
T6(x) = 32x6  48x4 + 18x2  1 Remarks
The graphs of first four Chebyshev polynomials are as shown in the fig. 8.2 below:

Tn(x)

T3(x) (0,1) T1(x)


T4(x)

T2(x)
x
(1,0) 0 (1,0)

(0,1)

Fig. 8.2
16.9.1 Powers of x in Terms of Chebyshev Polynomials
From above six Chebyshev polynomials, we find
1 = T0(x)
x = T1(x)

Similarly, we can express higher degree of x in terms of Chebyshev polynomials.


16.9.2 Orthogonal Properties of Chebyshev Polynomials

(i)
Approximation 245

(ii)
Remarks Proof : (i) Since Tm(x) = cos m, Tn(x) = cos n where x = cos , then

=0
If m = n  0, then

If m = n = 0, then

Proof : Since Un(x) = sin n, Um(x) = sin m, where x = cos 

= 0.
If m = n  0, then

If m = n = 0, then
246 Programming in C and Numerical Analysis

16.9.3 Chebyshev Polynomial Approximation


In approximation theory, one uses monic polynomial, that is Chebyshev polynomials in which the
coefficient of xn is unity.

≤ 2 x ∈ [1, 1].
Remarks
1 n
Since | Tn(x) | ≤ 1, then
Thus, in Chebyshev approximation, the maximum error is kept down to a minimal. This is often
referred to as minimax principle and the polynomial T n(x) is called the minimax polynomial. By this
process we can find lower-order approximation, which is called minimax approximation to a given
polynomial.
Let a0 + a1x + a2x2 + …. + anxn be the required minimax polynomial approximation for a
continuous function f(x) defined on the interval [1, 1]. Suppose that

(1)
is the Chebyshev series expansion for f(x). Then the partial sum Sn(x) of (1) given by

(2)
is very close to the solution to the problem.


Hence, the partial sum (2) is the best uniform approximation to f(x).
16.9.4 Chebyshev Equioscillation Theorem : If f(x) be a continuous function on [a, b] and p(x)
by its best uniform approximation then by minimax principle.

Let us take
and (x) = f(x)  pn(x)
then there are (n + 2) points a = x0 < x1 < x2 < …..< xn < xn+1 = b such that
(i) (xi) =  En for i = 0, 1, 2, …, n + 1
(ii) (xi)  (xi+1) for i = 0, 1, 2, …, n
with the help of the conditions (i) and (ii) we can find the best uniform approximation.
Example 1 : Find the best lower-order approximation to the cubic 2x3 + 3x2.
Solution : Since we know that T1(x) = x

and

Thus the polynomial is the required lower-order approximation to the given cubic

with a maximum error  in [1, 1].


Approximation 247

Example 2 : Prove that :


Solution : Since Tn(x) = cos n, Un(x) = sin n
where x = cos 
R.H.S. = Un+1(x)  xUn(x)
= sin(n + 1)   cos  sin n
= sin n cos  + cos n sin   cos  sin n
Remarks = sin  cos n

= = R.H.S.

Example 3 : Economize the power series :

to three significant digit accuracy.

Solution : Since
will produce a change in the fourth decimal place only. So that the truncated series is

(1)

(2)
Converting (1) into Chebyshev polynomials by using (2), we obtain

or (3)

Since will produce a change in the fourth decimal place only, so again truncated
series is

(4)
248 Programming in C and Numerical Analysis

The economized series is therefore give by

.
This gives sin x to three significant digit accuracy.

Remarks
Example 4 : Express T0(x) + 2T1(x) + T2(x) as a polynomials in x.
Solution : Since T0(x) = 1, T1(x) = x and T2(x) = 2x2  1
 T0(x) + 2T1(x) + T2(x) = 1 + 2x + 2x2  1 = 2x2 + 2x

Example 5 : Express 1  x2 + 2x4 as sum of Chebyshev polynomials.


Solution : Since

and
T0(x) = 1

Example 6 : By the method of least squares, find the straight line that best fits the following data :

x: 1 2 3 4 5
y: 14 27 40 55 68

Solution : Let the straight line to be fitted to the data be


y = a + bx (1)
then the normal equations are
y = na + bx (2)
and xy = ax + bx2 (3)
The table is given below :
Approximation 249

x y xy x2
1 14 14 1
2 27 54 4
3 40 120 9
4 55 220 16
5 68 340 25
x = 15 y = 204 xy = 748 x = 55
2

Here n = 5, x = 204, xy = 748, x = 55, substituting these values in (2) and (3), we get
2

204 = 5a + 15b
and 748 = 15a + 55b
Solving these equations, we get a = 0, b = 13.6
Hence, the line of best fit is y = 13.6x
Remarks Exercise  16.1
Question 1 : Fit a straight line to the following data :
x: 1 2 3 4 5 6
y: 1200 900 600 200 110 50
Question 2 : Fit a straight line to the following data :
x: 0 5 10 15 20 25
y: 12 15 17 22 24 30
Question 3 : Find the least square line y = a + bx for the data :
x: 2 1 0 1 2
y: 1 2 3 3 4
Question 4 : Fit a straight line to the given data :
x: 1 2 3 4 6 8
y: 2.4 3.1 3.5 4.2 5.0 6.0
2
Question 5 : Find the parabola of the form y = a + bx + cx which fits most closely with the
observations :
x: 3 2 1 0 1 2 3
y: 4.63 2.11 0.67 0.09 0.63 2.15 4.58
2
Question 6 : Fit a parabola y = a + bx + cx to the following data :
x: 1 2 3 4 5 6 7 8 9
y: 2 6 7 8 10 11 11 10 9
Question 7 : Determine the constants a and b by the method of Least Squares such that y = ae bx fits
the following data :
x: 2 4 6 8 10
y: 4.077 11.084 30.128 81.897 222.62
250 Programming in C and Numerical Analysis

Question 8 : For the data given below, find the equation to the best fitting exponential curve of the
form y = aebx
x: 1 2 3 4 5 6
y: 1.6 4.5 13.8 40.2 125 300
Question 9 : Fit an exponential curve of the form y = abx to the following data :
x: 1 2 3 4 5 6 7 8
y: 1 1.2 1.8 2.5 3.6 s 4.7 6.6 9.1
Question 10 : Express 1 + x  x2 + x3 as sum of chebyshev polynomials.

Question 11 : Prove that


Remarks

Question 12 : Prove that


Question 13 : Economize the power series

Question 14 : Economize the series

On the interval [1, 1] allowing for a tolerance of 0.0005.

Answers  16.1
Question 1 : y = 1361.97  243.42x
Question 2 : y = 11.285 + 0.7x
Question 3 : y = 2.6 + 0.7x
Question 4 : y = 2.0253 + 0.502x
Question 5 : y = 1.243  0.004x + 0.22x2
Question 6 : y = 0.98 + 3.55x  27x2
Question 7 : a = 1.49989; b = 0.50001; y = 1.49989e0.50001x
Question 8 : y = 0.5580e1.0631x
Question 9 : y = 0.6823(1.384)x

Question 10 :
Approximation 251

Keywords : Least square method, approximation.


Summary : In this unit we discussed, various types of fitting the curves from the numerical data. On
the basis of this mathematical equation, predictions can be made in many statistical investigations.
Least squares method is the best curve fitting method and is easily implemented on computers.

You might also like