Programming in C and Numerical Analysis
Programming in C and Numerical Analysis
Remarks
Primary Memory Secondary
Memory
RAM ROM
Central Processing
Arithmetic
Unit
and logic unit
Keyboard Printer
(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 2r. 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 = 2r, 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
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
Calculate Circumference
c = 2**r
Print circumference c
STOP
Algorithms and Flowcharts 7
Read a, b, c
Disc = b2 4ac
Is
Disc>0?
Yes
disc) / 2a
STARTT
8 Programming in C and Numerical Analysis
START
Yes If No
a>b
Yes If No No If Yes
a>c b>c
STOP
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?
Print Fact
STOP
10 Programming in C and Numerical Analysis
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
STOP
Algorithms and Flowcharts 11
START
Read n
Is Yes
Print “Number is prime”
n=2
No
i=1
STOP
i=i+1
12 Programming in C and Numerical Analysis
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
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
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.1025655105 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
Integer Character
signed unsigned
int unsigned int char
short int unsigned short int signed char
long int unsigned long int unsigned char
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 :
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.
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.
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.
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.
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
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.
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).
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
No
Link the program
No
No
Display result
STOP
30 Programming in C and Numerical Analysis
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
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.3.2 Combined precedence table for arithmetic operators and relational operators
(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
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=ab
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;
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.
int
unsigned int
long int
float
double
long
double
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
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*(sx)*(sy)*(sz);
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
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)
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
Entry Remarks
Statement block
Rest of Program
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
Entry
False
True
Test expression1
True False
Test expression2
Rest of Program
{
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
Rest of Program
Program :
Write a program to calculate gross salary of an employee.
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);
}
………………….
………………….
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
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
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
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
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 :
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
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
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.
#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
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
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.
0 1 2 3
Num 100.0 2.0 3.4 50.0
{
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
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
#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
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
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
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
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
Output
The two strings are not same.
The first four characters are same.
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
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);
……
……
}
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);
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
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
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.
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.
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
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
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
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
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
CHAPTERVIII
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
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,
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.
(1)
So, the 1st approximation to the root of f(x) = 0 is given by putting y = 0 in equation (1), so we get
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
Now, the Abscissa of the point where it crosses the x-axis 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 42.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)
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
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
Remarks
x1 = 1.871
2nd Approximation is
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
Here,
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
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
(3)
For x = a + 2h, f(a + 2h) = G0 + G1.2h + G2(2h).h
G2.2h2 = f(a + 2h) G0 G1.2h
G2 =
Similarly, we have
………………………
………………………
f(x) = f(a) + (x a) + (x a) (x ).
+ (x a) (x ) (x ) + …….
Remarks
x = (u )h,
Now putting all these values in (4), we have
….+(uh) (u 1) h…(u )h
….+
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.
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 a15
a8 a14 815a
4 a(say) a12 664a
32a 523a
5 32 402a
Now we put 5y = 0, we get 81 – 5a = 0.
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
where x = x0 + uh
Here h = 1, x0 = 0, therefore, u = x
= 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
We shall find the number of students with marks less than 45.
Remarks
For x = a + :
f(a + h) = G0 + G1(2h) + G2(2h)(h)
2
2h G2 = f(a + ) G0 + 2h.G1
= ∇2f(a + nh)
h)
Similarly,
………………
………………
132 Programming in C and Numerical Analysis
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
.
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
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
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
Remarks
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.
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
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
= 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
0.7638 0.0076
33 1 16.3432 0.0640
0.8278
37 2 15.5154
Remarks
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
∇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
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)
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 :
Let us take .
Remarks
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
(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
Remarks
EXERCISE 9.2
f(20) = 3010, f(25) = 3979, f(30) = 4771, f(35) = 5441, f(40) = 6021.
0 5 10 15 20 25 30
Question 4 : Apply Bessel’s formula for finding the value of y for x = 3.75, given that
ANSWERS
144 Programming in C and Numerical Analysis
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) =
Remarks
i.e.
………………...
…………………
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
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].
x 0 1 2 3
y(x) 1 0 1 10
x1 = 1 y1 = 0
x2 = 2 y2 = 1
x3 = 3 y3 = 10
x 5 7 11 13
y 150 392 1452 2366
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
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
- 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
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
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
x f(x) f (x)
0 0 1
4 2 0
Now
Interpolation with Unequal Intervals 155
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
x: 1 0 2 3 7 10
f(x): 11 1 1 1 141 561
156 Programming in C and Numerical Analysis
(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
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)
(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
(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
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
(iv)
At x = xn, we get u = 0. So equation (iii) becomes
(v)
Also, equation (iv) becomes
(vi)
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
= 1.49133
11.4 DERIVATIVES USING STERLING CENTRAL DIFFERENCE FORMULA
(i)
Since Remarks
Now,
(ii)
i.e.
or (iii)
For tabulated value at x = x0, we have u = 0
and
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)
60 2 28.2
10.0
75 1 38.2 5.0
5.0 2.3
162 Programming in C and Numerical Analysis
Bessel’s formula used when u lies between and and also fai u = fai find
From Bessel’s formula, we have
(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 :
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
Putting u = 0, we get
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
f (x) = f(x0) + (2x – x0 – x1) f(x0) + [3x2 – 2x(x0 + x1 + x2) + x0x1 + x1x2
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
f(x) = f(x0)+(x – x0) f(x0)+(x – x0)(x – x1) f(x0)+(x – x0)(x – x1)(x – x2) f(x0)
f (x) = f(x0) + (2x – x0 – x1) f(x0) + [3x2 – 2x(x0 + x1 + x2) + x0x1 + x1x2
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
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
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
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
(*)
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
=
= 1.8276
(3.1)
Similarly,
170 Programming in C and Numerical Analysis
(3.2)
(3.3)
Remarks ………………………………..
Example 1 : Using Simpson’s rule to evaluate using six sub-intervals and hence find an
approximate value of loge4.
Solution : Let I =
I=
I=
= 0.5351
Therefore, = 0.5351
(4.1)
Similarly,
(4.2)
(4.3)
……………………………………….
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
= 1.4108
(ii) By Simpson’s one-third rule, we have
= 1.3662
(iii) By Simpson’s three-eighth rule, we have
= 1.3571
Remarks
(5.1)
Similarly, we can get
(5.2)
…………………………………………………………….
Exercise 12.1
174 Programming in C and Numerical Analysis
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)
(7)
(8)
(9)
Thirdly, we elimination of z from (7) and (8), we get
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
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
l11u12 = 3 u12 =
l11u13 = 1 u13 =
Remarks (3) Comparing the 22nd and 32nd position, we get
l33 = 2 3 (5) = 18
Now AX = Bas LUX = B
Put UX = Z
LZ = B
Now UX = Z
Remarks
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
(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)
=
x = b1 a12y a13z
=
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 LLX = B
from LX = Z, we get LZ = B
from LZ = B, we get z1, z2,…,zn and put these values in LX = 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(LX) = B
or LZ = B, where Z = LX
Consider LZ = B
z1 = 5
z1 + z2 = 6 z2 = 1
z1 + z2 + z3 = 8 z3 = 2
Z=
Now, LX = 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)
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
(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
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)
Initial approximation :
First iteration :
Therefore,
190 Programming in C and Numerical Analysis
Second Iteration :
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
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.1117 60+211.111+30
0 + 4 0 = 0.001 5
=11.111
x = 11.111
100 – 9 80 + 11.111 – 7 60 + 2 11.111 + 3
13.016+30 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
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
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
(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
Keywords:-
Simultaneour Linear Algebraic Equations 197
Summary :-
We have discussed various direct or indirect methods of solving system of linear equations with
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 182 + 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
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) =
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.
BX(0) =
BX(1) =
.
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
B= (1)
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
(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
= (7)
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
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
We now obtain
Remarks
i.e.,
Now the eigen vectors of A are the columns of P.
(1)
and the orthogonal rotation matrix, B1 in the plane (2, 3) as
(2)
i.e.,
(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).
Here
Remarks
Now,
| A1 I | =
The Sturm sequence {fn} is defined as
f0() = 1
f1() = 1
= 2 4 5
Eigen Value Problems 209
i.e.,
Remarks
which gives
y3 = 0
On solving, we get y1, y2 = , y3 = 0
Hence
Required eigen vector of A = B1Y
ww = I = ww
(2)
Now, P = (I 2ww)
= I 2(w)(w) = I 2ww = P
P is a symmetric matrix
Also, PP = (I( - 2ww)(I 2ww) = (I 2ww)(I 2ww)
= I 4ww + 4wwww = 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 33 i.e. Remarks
A
w is of order 3 1 and w is of order 13
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
(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)
Also,
Now,
Eigen Value Problems 213
Remarks
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.
(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
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
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)
Answers 14.1
Question 2 : (i)
(ii)
218 Programming in C and Numerical Analysis
Remarks
Question 4 :
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)
, 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.
f(x, y) =
222 Programming in C and Numerical Analysis
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
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
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
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
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
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
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
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
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 :
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
= 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
k = 0.1325
y2 = y1 + k = 1.2429
Hence the value of y at x = 0.2 is 1.2429.
From above
Putting these values
But
Hence
= 0.232 (Approx)
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
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
(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
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
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.
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).
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
Putting i = 2, we get
24y3 47y2 + 24y1 = 0 (3)
Put i = 3, we get
234 Programming in C and Numerical Analysis
Where and
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 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
= 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
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.
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 + bx, xy = ax + bx2
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
x: 1 2 3 4 5
y: 2 4 6 8 10
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
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
= 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
X X4=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
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
Tn(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)
(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
≤ 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
= = R.H.S.
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
.
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
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
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.
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