Programming in C Data Structures (15pcd13) - Notes PDF
Programming in C Data Structures (15pcd13) - Notes PDF
in
Programming in C and Data Structures 15PCD13
in
The objectives of this course is to make students to learn basic principles of Problem
solving, implementing through C programming language and to design & develop
programming skills. To gain knowledge of data structures and their applications
Module -1 : INTRODUCTION TO C LANGUAGE
n.
Teaching
Hours
Pseudo code solution to problem, Basic concepts in a C program,
Declaration, Assignment & Print statements, Data Types,
exercise.
Text 1: Chapter 2, and
tio
operators and expressions etc, Programming examples and
exercises.
Text 1: Chapter 3. & Text 2: 4.4.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
arrays, Dynamic memory allocations methods, Introduction to
Preprocessors, compiler control Directives, Programming examples
and exercises.
n.
10
Text 1: 5.1 to 5.6, 5.8. Text 2: 12.2, 12.3, 13.1 to 13.7.
H o ur s
Introduction to Data Structures: Primitive and non primitive
data types, Abstract data types, Definition and applications of
tio
Stacks, Queues, Linked Lists and Trees.
Text 2 : 14.1, 14.2, 14.11, 14.12, 14.13, 14.15, 14.16, 14.17, 15.1.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Text Books:
1. Brian W. Kernighan and Dennis M. Ritchie: The C Programming
Language, 2nd Edition, PHI, 2012.
2. Jacqueline Jones & Keith Harrow: Problem Solving with C, 1st
Edition, Pearson 2011.
Reference Books:
1. Vikas Gupta: Computer Concepts and C Programming, Dreamtech
Press 2013.
2. R S Bichkar, Programming with C, University Press, 2012.
in
3. V Rajaraman: Computer Programming in C, PHI, 2013.
n.
tio
lu
u so
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Table Of Content P ag e n o
MO D U L E I
I NT RO D U C T I O N T O C L A N G U A G E 6
in
MODULE II
n.
Two way selections (if, if-else, nested if-else, cascaded if-else),
Switch statement,
tio
Ternary operator? Go to, Loops (For, do-while, while) in C,
Break and continue, programming examples and exercises.
MODULE III
lu
ARRAYS, STRINGS AND FUNCTIONS: 50
FUNCTIONS
Functions in C,
Argument Passing – call by value, Functions and
Program structure,
Location of functions,
Void and parameter less Functions,
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Recursion
Programming examples and exercises.
MO D U L E I V
in
Defining, opening and closing of files
Input and output operations
n.
Programming examples and exercises
MO D U L E V
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
MODULE I
INTRODUCTION TO C LANGUAGE
1. Calculating a tip
2. Double checking a grocery receipt
in
3. Automating LaTeX to HTML conversion
n.
Also known as the software life cycle
Starting from the problem statement:
1. Requirements specification --- removal of ambiguity from the problem
statement
(acquiring expertise)
tio
2. Analysis --- a detailed determination of the problem inputs and outputs
3. Design --- the development of a logically-ordered set of steps, whose application
lu
to the problem input produces the problem output
4. Implementation --- the creation of a working program from the design
5. Testing and verification --- of the working program
so
6. Documentation
i. The problem being solved
ii. Who is responsible?
iii. The design
u
Algorithm:
A sequence of a finite number of steps arranged in a specific logical order which, when
executed, produces the solution for a problem.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
2. Output
3. Unambiguousness --- computers don't accept ambiguity
4. Generality --- solves a class of problems
5. Correctness --- correctly solve the given problem
6. Finiteness --- termination
7. Efficiency --- recognition of finite computing resources: CPU cycles, memory
Pseudocode:
in
• Meta-programming language
• Algorithm representation
n.
C. Bohm and G. Jacopini proved in 1966 than pseudocode required only three structural
el em en t s
E x am p l e:
lu
print "What is your name?"
read n am e
print "How old are you, ", name, "?"
so
read ag e
let birthYear = CURRENT_YEAR - age
begin
let amountDue = overDue + currentBilling + penalty
print "You owe: ", amountDue
vt
end
if condition
then_part
else
else_part
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
end_if
• A single statement
• A set of statements enclosed by begin/ end
if payment is overdue
begin
let amountDue = pastDue + currentBilling + penalty
print "You owe: ", amountDue
end
else
in
print You owe: , currentBilling
end_if
n.
i f g rad e < 6 0
print "F"
else_if grade < 70
print "D" tio
else_if grade < 80
print "C"
else_if grade < 90
print "B"
else
lu
print "A"
end_if
Specifies a block of one or more statements that are repeatedly executed until a
condition is
satisfied.
while condition
u
loop_body
end_while
vt
Structure of loop_body
let sum = 0
while there are input numbers to sum
begin
print "Next number: "
read n u m b er
let sum = sum + number
end
end_while
print "The sum is: ", sum
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
C language Preliminaries
in
1. C is a robust language , which consists of number of built-in functions and
operators
n.
2. Programs written in c are executed fast compared to other languages.
3. C language is highly portable
tio
4. C language is well suited for structured programming.
5. C is a simple language and easy to learn.
Introduction to C Language
Structure of a C program:
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Executable Part
}
Subprogram section
Function 1
Function 2
.
.
.
Function n
in
The documentation section consists of a set of comment lines giving the name of the
program, the name author and other details which the programmer would like to use later.
n.
The link section provides instructions to the compiler to link functions from the s ystem
l ibrary. The d efinition section contains all symbolic constants. There are some variables
that are used in more than one function. Such variables are called global variables and are
tio
declared in the global declaration section. Every C program must have one main() function
section. This section contains two parts declaration part and executable part. The
declaration part declares all the variables used in the executable part. There should be at
least one statement in the executable part. These two parts must appear between the
lu
opening and the closing braces. The program execution begins at the opening brace and
ends at the closing brace. The closing brace of the main function section is logical end of
so
the program. All statements in the declaration and executable parts end with a semicolon.
The subprogram section contains all the user-defined functions that are called in the main
function. The main function is very important compared to other sections.
u
Character Set
vt
The characters that can be used to form words, numbers and expressions depend
upon the computer on which the program is run. The characters in C are grouped
into the following
categories.
1. Letters
2. Digits
3. Special characters
4. White Spaces
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Letters Digits
Uppercase A…Z All decimal digits 0…9
Lowercase a….z
Sp eci al ch aract er s
, comma & ampersand
. period ^ c a ra t
; semicolon *asterisk
: colon -minus sign
? question mark + sign
in
‘ apostrophe < o p e n i n g an g l e b rack et
! exclamation mark (or less than sign)
| vertical bar > closing angle bracket
n.
/ slash (or greater than sign)
\ backslash ( left parenthesis
~ tilde tio ) right parenthesis
_ underscore [ l e ft b ra ck e t
$ dollar sign ] right bracket
% percent sign { l e ft b ra c e
lu
# number sign } right brace
White Spaces
so
Bl an k Sp ace
Horizontal tab
C a rri ag e re t u rn
u
New line
Fo rm fe e d
vt
Identifiers:
In c language every word is classified into either keyword or identifier. All keywords have
fixed meanings and these meanings cannot be changed. These serve as basic building blocks for
program statements. All keywords must be written in lowercase. The list of all ANSI C
keywords are listed below.
ANSI C Keywords
auto double int struct
b reak else long switch
case en u m register t y p ed ef
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
Integer Constants:
n.
An integer constant refers to a sequence of digits. There are three types of
integers, namely decimal, octal and hexadecimal. Decimal integers consist of a set of digits 0
through 9, preceded by an optional – or + sign. Some examples of decimal integer constants are
123
-431
0
tio
34567
lu
+678
Spaces, commas, and non-digit characters are not permitted between digits. For example
so
15 750
20,000
Rs 1000
u
037
0
0435
0567
A sequence of digits preceded by 0x is considered as hexadecimal integer. They may
also include alphabets A through F or a through F. The letters A through F represent the
numbers 10 through 15. The examples for hexadecimal integers are:
0x2
0x9F
Dept. of ISE, vtusolution.in Page 12
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
0xbcd
0x
Floating-point constants:
Integer numbers are inadequate to represent quantities that vary continuously, such as distances
,heights ,temperatures ,prices and so on. These quantities are represented by numbers containing
fractional parts like 23.78. Such numbers are called floating-point constants or real constants.
Examples for floating-point constants are given below.
213.
.95
in
-.71
+.5
A real number may also be expressed in exponential(or specific notation). For example the value
n.
213.45 may be written as 2.1345e2 in exponential notation. e2 means multiply by 102. The
g en e ral fo rm i s
mantissa e exponent
Character Constants:
tio
A character constant contains a single character enclosed within a pair of single quote
marks. Examples of character constants are:
‘5’ ‘X’ ‘;’ ‘ ‘
lu
Note that the character constant ‘5’ is not the same as the number 5. The last constant is a blank
space. Character constants have integer values known as ASCII values. For Example, the
statement
so
on character constants.
Backslash Character Constants:
vt
C supports some special backslash character constants that are used in output functions.
For example, the symbol ‘\n’ stands for new line character. The below table gives you a
list of backslash constants.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
‘\r’ c a rri ag e r e t u rn
in
characters.
These character combinations are called escape sequences.
String constants:
n.
A string constant is a sequence of characters enclosed in double quotes. The letters may
be numbers, special characters and blank space.
Examples are given below “THANK YOU”
“2345”
tio
“?.....”
“7+8-9”
lu
“X”
Remember that a character constant ‘X’ is not equivalent to the single character string constant(
“X”). A single character string constant does not have an equivalent integer value as a
so
single character constant. These type of constants are used in programs to build meaningful
programs.
Meaning of variables:
A variable is a data name that may be used to store a data value. Unlike the constants that remain
u
below.
Average
Height
Total
Counter_1
Rules for defining variables:
Variable names may consist of letters, digits, and the underscore(_) character, subject to the rules
given below:
1. The variables must always begin with a letter. Some systems permit underscore as the
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
first character.
2. ANSI standard recognizes a length of 31 characters. However, the length should not
be normally mare than eight characters. Since first eight characters are treated
as significant by many compilers.
3. Uppercase and lowercase are significant. That is ,the variable Rate is not the same as
rate or TOTAL.
4. The variable name should not be a keyword.
5. White space is not allowed.
Some examples are given below:
Abhi Value I_ rat e
in
Mumbai s1 ph_value
Rate sum1 distance
n.
The examples given below are invalid:
345 (rate)
% 56 nd
Declaration of variables:
tio
Identifiers which are used as variable names should be prefixed as integer or float
by the following declaration should appear at the beginning of a program before the
variable names are used.
lu
type _name variable name……variable name;
The t ype_name is alwa ys a reserved word. The type_name available for variable names storing
numbers are int for integers and float for floating point numbers. Valid examples are
so
given below:
int n, height ,count ,digit;
float rate, average , y_coordinate,p1;
u
When a variable name is declared then a memory location is identified and given this name.
The following declarations of variables are invalid:
vt
from machine to machine. The variety of data types available allow the programmer to select the
appropriate to the needs of the application as well as the machine. The fundamental or primary
Dept. of ISE, vtusolution.in Page 15
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
and signed. The range of basic four types are given below:
Data types Ra n g e o f v al u es
ch ar -128 to 127
in
Char, int, float and double are all keywords and therefore their use is reserved. They may not be
n.
used as names of variables. Char stands for “character” and int stands for “integer”. The
keywords short int, long int and unsigned int may be and usually are, shortened to just
short, long, and unsigned, respectivel y. Also, double and long float are equivalent, but double
tio
is the keyword usually used.
Integer Types:
Integers are whole numbers with a range of values supported by a particular machine. Generally
lu
integers occupy one word of storage. If we use a 16 bit word length, the size of the integer
value is limited to the range -32768 to +32767. A signed integer uses one bit for sign and 15 bits
for the magnitude of the number. Similarly, a 32 bit word length can store an integer
so
ranging from -2,147,483,648 to 2,147,483,647. C has three classes of integer storage, namely
short int, int, and long int in both unsigned and signed forms. For example, short int represents
fairly small integer.
Values and requires half the amount of storage as a regular int number uses. Unlike
u
signed integers, unsigned integers use all the bits for the magnitude of the number and are
always positive. Therefore, for a 16 bit machine, the range of unsigned integer numbers will be
vt
from 0 to 65,535. We declare long and unsigned integers to increase the range of values.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Character types:
A single character can be defined as a character (char) type data. Characters are usually stored in
8 bits(one byte) of internal storage. The qualifier signed or unsigned may be explicitly applied to
char. While unsigned chars have values between 0 and 255, signed chars have values from -128
to 127.
in
Unsigned char 8 0 to 255
n.
Sh o rt i n t o r 8 -128 to 127
Scanf functions:-
The function scanf() is used to read data into variables from the standard input, namely
vt
integers. The integers will be separated by a blank in the data typed on the keyboard.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
456 18578
Observe that the symbol &(called ampersand) should precede each variable name. Ampersand is
used to indicate that the address of the variable name should be found to store a value in it. The
manner in which data is read by a scanf statement may be explained by assuming an arrow to be
positioned above the first data value. The arrow moves to the next data value after storing
the first data value in the storage location corresponding to the first variable name in the list. A
blank character should separate the data values. The scanf statement causes data to be read from
one or more lines till numbers are stored in all the specified variable names.No that no blanks
should be left between characters in the format-string. The symbol & is very essential in
in
front of the variable name. If some of the variables in the list of variables in the list of
variables in scanf are of type integer and some are float, appropriate descriptions should be used
in the format-string.
n.
For example:
Scanf(“%d %f %e”, &a , &b, &c);
tio
Specifies that an integer is to be stored in a, float is to be stored in b and a float written using the
exponent format in c. The appropriate sample data line is:
Printf function:
lu
The general format of an output function is
Printf(format-string, var1,var2…..varn);
so
Where format-string gives information on how many variables to expect, what type
of arguments they are , how many columns are to be reserved for displaying them and
any character string to be printed. The printf() function may sometimes display only a message
and not any variable value. In the following example:
u
And there are no variables. This statement displays the format-string on the video display
and there are no variables. After displaying, the cursor on the screen will remain at the end
of the string. If we want it to move to the next line to display information on the next line, we
should have the format-string:
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
the variable a is of type int and b of type float or double. % d specifies that a is to be displayed as
in
# include<stdio.h>
m a i n ()
n.
{
int a= 45, b= 67
printf(“Output:\n”);
printf(“1,2,3,4,5,6,7,,8,0\n”);
tio
printf(“\n”);
lu
printf(“%d, %d,,%f ,%f \n” , a,b,x,y);
printf(“\n”);
so
Output:
1234567890
u
45,67,45.78,34.90
vt
#include<stdio.h>
m a i n ()
{
int a,b,c,d;
float x,y,z,p;
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
printf(“End of display”);
}
in
Input:
n.
-768 0362 abf6 3856 -26.68 2.8e-3 1.256e22 6.856
Output:
End of display
so
The function scanf is the input analog of printf, providing many of the same conversion facilities
in the opposite direction.
u
in format, and stores the results through the remaining arguments. The format argument
is described below; the other arguments, each of which must be a pointer, indicate where
the corresponding converted input to be stored. scanf stops when it exhausts its format
string, or when some input fails to match the control specification. It returns as its value the
number of successfully matched and assigned input items. This can be used to decide how many
items were found. On end of file EOF is returned; note that this is different from 0, which
means that the next input character does not match the first specification in the format string.
The next call to scanf resumes searching immediately after the last character already
converted. A conversion specification directs the conversion of the next input field. Normally
the result is placed in the variable pointed to by the corresponding argument. If assignment
suppression is indicated by the * character, however, the input field is skipped; no assignment is
Dept. of ISE, vtusolution.in Page 20
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
made. An input field is defined as a string of non-white space characters; it extends either to
the next white space character or until the field width, if specified, is exhausted. This
implies that scanf will read across line boundaries to find its input, since new lines are white
space. (White space characters are blank, tab, new line, carriage return, vertical tab and form
feed).
T h e g en e ral s y n t ax i s
in
to printf. Each conversion specification begins with a % and ends with a conversion character.
Between the % and the conversion character there may be in order:
n.
• A number that specifies the minimum field width. The converted argument will
be printed in a field at least this wide. If necessary it will be padded on the left or right, to
make up the field width.
•
tio
A period, which separates the field width from the precision.
complementary to the character input function getchar. The putchar function, like getchar, is
u
a part of the standard C I/O library. It transmits a single character to a standard output device.
The character being transmitted will normally be represented as a character type variable. It
vt
must be expressed as an argument to the function, enclosed in parentheses, following the word
putchar.
T h e g en e ral s y n t ax i s
putchar(character variable)
where character variable refers to some previously declared character variable.
Char c;
…… …
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
putchar(c);
C programs:
1) Program to demonstrate printf statement
#include<stdio.h>
m a i n ()
{
printf(“hello, world\y”);
printf(“hello, world\7”);
in
printf(“hello, world\?”);
}
n.
2) Program to convert farenheit to Celsius
#include<stdio.h>
main()
{
tio
float fahr, Celsius;
lu
printf(“ enter the value for farenheit\n”);
Celsius=(5.0/9.0)*fahr-32.0;
#include<stdio.h>
m a i n ()
{
int number;
If (number<100)
{
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Output
Enter an integer number 54
in
Your number contains more than digits
n.
#include<stdio.h>
m a i n ()
{
int year,period;
float amount,inrate,value;
tio
printf(“Input amount , interest rate and period \n\n”);
lu
scanf(“%f %f %d”, &amount, &inrate,&period);
printf(“\n”);
year=1;
so
while(year<=period)
{
value amount + inrate*amount;
printf(“%2d Rs. %8.2f\n”, year, value);
u
amount=value;
vt
year=year+1;
}
}
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
average= sum/N;
printf(“N=%d Sum= %f”, N, sum);
printf(“Average=%f”, average);
n.
}
#include<stdio.h>
m a i n ()
tio
6) Program to convert days to months and days
{
lu
int months,days;
printf(“enter days \n”);
so
scanf(“%d”, &days);
months=days/30;
days=days%30;
printf(“Months = %d Days= %d”, months,days);
u
}
Types of operators and expressions,
vt
Arithmetic operators:
C provides all the basic arithmetic operators. The operators +,-,* and / all work the same way as
they do in other languages. These can operate on any built-in data type allowed in C. The unary
minus operator, in effect, multiplies its single operand by -1. Therefore, a number preceded by a
minus sign changes its sign.
Operator M ean i n g
+ Addition or unary plus
- Subtraction or unary minus
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
* Multiplication
/ Division
% Modulo division
Integer division truncates any fractional part. The modulo division produces the remainder of an
integer division.
E x a m p l e s a re:
a-b a+b
a*b a/b
in
a%b -a * b
Here a and b are variables and are known as operands. The modulo divison operator % cannot be
n.
used on floating point data.
Arithmetic expressions:
An arithmetic expression is a combination of variables, constants and operators arranged as per
tio
the syntax of the language. Expressions are evaluated using an assignment statement of the form
Variable=expression;
The table below shows the algebraic expression and C language expression
Algebraic expression C expression
lu
a x b-c a*b-c
(m + n) (x + y) (m + n) *(x + y)
so
(a b )/ c a*b/c
3x2+2x+1 3*x*x+2*x+1
x/y +c x/y + c
Variable is any valid C variable name. When the statement is encountered, the expression
u
is evaluated first and the result then replaces the precious value of the variable on the left-
hand side. All variables used in the expression must be assigned values before evaluation is
vt
attempted.
x=a*b-c;
y=b/c*a;
z=a-b/c+d;
The blank space around an operator is optional and adds only to improve readability. When these
statements are used in a program, the variables a ,b ,c and d must be defined before they are used
in the expressions.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Modes of expression:
There are three different modes of expression.
1. Integer Arithmetic
2. Real Arithmetic
3. Mixed-mode Arithmetic
Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers,
the expression is called an integer expression, and the operation is called integer arithmetic.
This mode of expression always yields an integer value. The largest integer value depends
on the machine, as pointed out earlier
in
E x am p l e:
n.
We have the following results:
a - b=10
a + b = 18
a * b = 56
a / b=3
tio
a %b=2
lu
During integer division, if both the operands are of the same sign, the result is truncated towards
zero. If one of them is negative, the direction of truncation is implementation dependent. That
is, 6/7=0 and -6/-7=0 but -6/7 may be zero -1 (Machine dependent).
so
Similarly, during modulo division , the sign of the result is always the sign of the
first operand(the dividend). That is
-14 % 3 =-2
u
-14 % -3= -2
14 % -3=2
Real Arithmetic
vt
x=6.0/7.0=0.857143
y= 1.0/3.0 =0.333333
z = -2 . 0 / 3 . 0 = -0 . 6 6 6 6 6 7
The operator % cannot be used with real operands.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
arithmetic expression. If either operand is of the real type, then only the real operation
is performed and the result is always a real number.
Thus
15/10.0=1.5
where as
15/10=1
in
In a program the value of any expression is calculated by executing one
arithmetic operation at a time. The order in which the arithmetic operations are executed in an
expression is based on the rules of precedence of operators.
n.
The precedence of operators is :
Unary (-) FIRST
Multiplication(*) SECOND
Division(/) and (%)
tio
Addition(+) and Subtraction(-) LAST
lu
For example, in the integer expression –a *b/c+d the unary- is done first, the result –a
is multiplied by b, the product is divided by c(integer division) and d is added to it. The answer
is thus:
so
-ab/c+d
All the expressions are evaluated from left to right. All the unary negations are done first. After
completing this the expression is scanned from left to right; now all *, / and % operations
are executed in the order of their appearance. Finally all the additions and subtractions are
u
Z=a + b* c
Initially b*c is evaluated and then the resultant is added with a. Suppose if want to add a with b
Use of parentheses:
Parentheses are used if the order of operations governed by the precedence rules are
to overridden. In the expression with a single pair of parentheses the expression inside
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
the parentheses is evaluated FIRST. Within the parentheses the evaluation is governed by
the precedence rules.
a * b/(c+d * k/m+k)+a
the expression within the parentheses is evaluated first giving:
c+dk/m+k
After this the expression is evaluated from left to right using again the rules of precedence giving
ab/c+dk/m+k +a
If an expression has many pairs of parentheses then the expression in the innermost pair
in
is evaluated first, the next innermost and so on till all parentheses are removed. After this
the operator precedence rules are used in evaluating the rest of the expression.
((x * y)+z/(n*p+j)+x)/y+z
n.
xy,np+j will be evaluated first.
Xy+z/np+j +x
tio
Will be evaluated. In the final scan the expression evaluated would be:
lu
(Xy+ z/np+j+x)/y +z
Increment and Decrement operators:-
The increment operator ++ and decrement operator – are unary operators with the
so
same precedence as the unary -, and they all associate from right to left. Both ++ and – can be
applied to variables, but no to constants or expressions. They can occur in either prefix or
postfix position, with possibly different effects occurring. These are usually used with integer
data type.
u
We use the increment and decrement statements in for and while extensively.
Consider the following example
m=5;
y=++m;
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statements as
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
m=5;
y=m++;
then the value of y would be 5 and m would 6. A prefix operator first adds to 1 to the
operand and then the result is assigned to the variable on left. On the other hand, a postfix
operator first assigns the value to the variable on left and then increments the operand.
Similar is the case, when we use ++(or--) in the subscripted variables. That is, the
statement a[i++]=10; is equivalent to
a[i]=10;
i=i+1;
The increment and decrement operators can be used in complex statements. Example
in
m=n++ -j+10;
Old value of n is used in evaluating the expression. n is incremented after the evaluation.
n.
Relational operators:
We often compare two quantities and depending on their relation, to take
certain decisions. For example, we may compare the age of two persons, or the price of two
tio
items, and so on. These comparisons can be done with the help of relational operators. C
supports six relational operators in all. These operators and their meanings are shown below
Relational Operators
Operator Meaning
lu
< is less than
> i s g re at e r t h an
so
>= i s g reat er t h an o r eq u al t o
== is equal to
u
!= is not equal to
A simple relational expression contains only one relational operator and has the following form:
vt
ae- 1 relational operator ae-2. ae-1 and ae-2 are arithmetic expressions, which may be
simple constants, variables or combination of them.
Given below are some examples of simple relational expressions and their values:
4.5<= 10 TRUE
4.5< 10 FALSE
-35>= 0 FALSE
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
a+b == c+d TRUE only if the sum of values of a and b is equal to the sum of values of
c
and d.
When arithmetic expressions are used on either side of a relational operator, the
arithmetic expressions will be evaluated first and then the results compared. That is,
arithmetic operators have a higher priority over relational operators. Relational expressions
are used in decision statements such as, if and while to decide the course of action of a running
program.
Logical operators:
In addition to the relational operators . C has the following three logical operators.
in
&& logical AND
|| logical OR
n.
! logical NOT
The logical operators && and || are used when we want to test more than one condition and make
decisions.
E x am p l e:
a>b && x == 10
tio
An expression of this kind which combines two or more relational expression is termed as
lu
a logical expression or a compound relational expression. Like the simple relational expressions
,a logical expression also yields a value of one or zero, according to the truth table shown
below.
so
The logical expression given above is true only if a>b is true and x==10 is true. If either
(orboth) of them are false, the expression is false.
Truth Table
Op-1 op-2 Value of the expression
u
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
We have seen that float or integer quantities may be connected by relational operators to yield an
Would have an answer true if marks is greater than or equal to 60 and false if marks is less than
60. The result of the comparison (marks>=60) is called a logical quantity. C provides a facility
in
subject and Mathematics as the subsidiary subject:
He should get 50 percent or more in Physics and 40 percent or more in Mathematics.
n.
If he gets less than 50 percent in Ph ysics he should get 50 percent or more in
Mathematics. He
should get atleast 40 percent in Physics. tio
If he gets less than 40 percent in Mathematics and 60 percent or more in Physics he is
allowed to
reappear in an examination in Mathematics to qualify.
In all the other cases he is declared to have failed.
lu
A Decision Table for Examination Results
so
Fai l - - - x
/*This program implements above rules*/
vt
include<stdio.h>
m a i n ()
{
unsigned int roll_no, physics_marks, chem_marks;
while(scanf(“%d %d %d”, &roll_no,&physics_marks, &chem_marks)!=EOF)
{
If(((chem_marks>=50 &&(physics_marks>=35)) ||
((chem_marks>=40))
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
&&(physics_marks>=50)))
Printf(“%d %d %d Pass\n”, roll_no, chem_marks, physics_marks);
Else If (( chem_marks>=60)) && physics_marks<35))
Printf(“%d %d %d Repeat Physics\n”, roll_no,physics_marks,chem_marks);
Else
Printf(“%d %d %d Failed \n”, roll_no, physics _marks, chem_marks);
}
}/*End while*/
}/*End main*/
in
Precedence of relational operators and logical operators:
E x am p l e:
(a>b *5) &&(x<y+6)
n.
In the above example, the expressions within the parentheses are evaluated first. The arithmetic
operations are carried out before the relational operations. Thus b*5 is calculated and after that a
within parentheses:
tio
is compared with it. Similarly y+6 is evaluated first and then x is compared with it. In general
The unary operations, namely, -,++,--,! (logical not) are performed first. Arithmetic operations
are performed next as per their precedence. After that the relational operations in each sub
lu
expressions are performed, each sub expression will be a zero or non _ zero. If it is zero it is
taken as false else it is taken as true.
Lastly the evaluated expression is assigned to a variable name as per the assignment operator.
The conditional operators:
u
x=3;
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
y=15;
z=(x>y)?x:y;
In this example, z will be assigned the value of b. This can be achieved using the if..else
statements as follows:
If (x>y)
z=x;
else
z=b;
in
Bitwise operators:
C has a distinction of supporting special operators known as bitwise operators for manipulation
of data at bit level. These operators are used for testing the bits, or shifting them right or
n.
left.
Bitwise operators may not be applied to float or double. where the filename is the
name containing the required definitions or functions. At this point, the preprocessor inserts the
tio
entire contents of the filename into the source code of the program. When the filename is
included within the double quotation marks, the search for the file is made first in the directory
and then in the standard directories.
Bitwise Operators
lu
Operator Meaning
& bitwise AND
so
! bitwise OR
^ bitwise exclusive OR
~ One’s Complement
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
First assigns the value 2 to a, then assigns 6 to b, and finally assigns 8(i.e 2+6) to value. The
comma operator has the lowest precedence of all operators,hence the parentheses are necessary.
Some examples are given below:
In for loops:
For(a=1, b=10;a<=b; a++, b++)
In while loops:
While(c=getchar(), C!=’10’)
Exchanging values:
in
T=x, x=y, y=t;
The precedence of operators among themselves and across all the set of operators:
Each operator in C has a precedence associated with it. This precedence is used to
n.
determine
how an expression involving more than one operator is evaluated. The operator at
the higher
level of precedence are evaluated first.
Operator
+
Description
Unary plus
tio
- Unary minus
lu
++ Increment
-- Decrement
! Logical negation
so
~ One’s Complement
& Address
size of(type) type cast conversion
u
* Multiplication
/ Division
vt
% Modulus
+ Addition
- Subtraction
<< left shift
>> Right shift
< less than
<= less than or equal to
> Greater than
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
= Assignment operators
*= / = %=
+= - = & =
n.
^= |=
<<= >>=
, Co m m a o p e ra t o r
tio
The associatively of operators:
The operators of the same precedence are evaluated either from left to right or from right to left
depending on the level. This is known as the associatively property of an operator. The table
below shows the associatively of the operators:
lu
Operators Associativity
() [ ] left to right
so
*/ %
<< >> left to right
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
If this expression is true, the expression ++x is evaluated. Other wise, the a/b is
evaluated. Finally, the assignment operation(+=) is carried out, causing the value of c to be
increased by the value of the conditional expression. If for example x, y, and z have the values
1,2,3 respectively, then the value of the conditional expression will be 2(because the
n.
expression ++a will be evaluated), and the value of z will increase to 5(z=3+2). On the other
hand, if x,y and z have the values 50,10,20 respectively, then the value of the conditional
expression will be 5(because the expression x/y will be evaluated) and the value of z will
increase to 25(z=20+5). tio
lu
u so
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
MODULE II
in
printf(...);
n.
like Pascal. Braces {and }are used to group declarations and statements together into a
compound statement, or block, so that they are syntactically equivalent to a single statement.
The braces that surround the statements of a function are one obvious example;
tio
braces around multiple statements after an if, else, while, or for are another.
else
so
statement2
where the else part is optional. The expression is evaluated; if it is true (that is, if expression
u
has a non-zero value), statement 1 is executed. If it is false (expression is zero) and if there
is an else part, statement 2 is executed instead. Since an if tests the numeric value of an
vt
expression, certain coding shortcuts are possible. The most obvious is writing if (expression)
instead of
if (expression!= 0)
Sometimes this is natural and clear; at other times it can be cryptic. Because the elsepart of an if-
elseis optional, there is an ambiguity when an else if omitted from a nested ifsequence. This
is resolved by associating the else with the closest previous else-less if. For example, in
if (n > 0)
if (a > b)
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
z = a;
else
z = b;
the else goes to the inner if, as we have shown by indentation. If that isn't what you want, braces
must be used to force the proper association:
if (n > 0) {
if (a > b)
z = a;
in
}
else
z = b;
n.
The ambiguity is especially pernicious in situations like this
if (n > 0)
if (s[i] > 0) {
tio
printf("...");
lu
return i;
else /* WRONG */
so
printf("error -- n is negative\n");
The indentation shows unequivocally what you want, but the compiler doesn't get the message,
and associates the else with the inner if. This kind of bug can be hard to find; it's a good idea
u
to use braces when there are nested ifs. By the way, notice that there is a semicolon after z = a in
if (a > b)
vt
z = a;
else
z = b;
The construction
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
in
else
statement
occurs so often that it is worth a brief separate discussion. This sequence of if statements is the
n.
most general way of writing a multi-way decision. The expressions are evaluated in order; if an
expression is true, the statement associated with it is executed, and this terminates the
whole chain. As always, the code for each statement is either a single statement, or a group of
tio
them in braces. The last else part handles the ``none of the above'' or default case where none of
the other conditions is satisfied. Sometimes there is no explicit action for the default; in that
case the trailing
else statement
lu
can be omitted, or it may be used for error checking to catch an ``impossible'' condition.
To illustrate a three-way decision, here is a binary search function that decides if a particular
value x occurs in the sorted array v. The elements of v must be in increasing order. The
function returns the position (a number between 0 and n-1) if x occurs in v, and -1 if not.
so
Binary search first compares the input value xto the middle element of the array v. If x is less
than the middle value,
searching focuses on the lower half of the table, otherwise on the upper half. In either case,
the next step is to compare xto the middle element of the selected half. This process of dividing
u
the range in two continues until the value is found or the range is empty.
vt
high = n - 1;
while (low <= high) {
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
mid = (low+high)/2;
if (x < v[mid])
high = mid + 1;
re t u rn m i d ;
in
return -1; /* no match */
The fundamental decision is whether xis less than, greater than, or equal to the middle
element v[mid]at each step; this is a natural for else-if. Our binary search makes two tests inside
n.
the loop, when one would suffice (at the price of more tests outside.) Write a version with
only one test inside the loop and measure the difference in run-time.
Switch
tio
The switch statement is a multi-way decision that tests whether an expression matches one of
a number of constant integer values, and branches accordingly.
lu
switch (expression) {
default: statements
}
u
default is optional; if it isn't there and if none of the cases match, no action at all takes place.
Cases and the default clause can occur in any order. we wrote a program to count the
occurrences of each digit, white space, and all other characters, using a sequence of if ... else
if ... else. Here is the same program with a switch:
#include <stdio.h>
{
int c, i, nwhite, nother, ndigit[10];
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
nwhite = nother = 0;
ndigit[i] = 0;
while ((c = getchar()) != EOF) {
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': ndigit[c-'0']++; break;
case ' ':
in
case '\n':
default: nother++;break;
n.
}
}
printf("digits =");
}
The break statement causes an immediate exit from the switch. Because cases serve just
as labels, after the code for one case is done, execution falls through to the next unless you
take explicit action to escape. Break and return are the most common ways to leave a switch. A
u
break statement can also be used to force an immediate exit from while, for, and do loops,
Falling through cases is a mixed blessing. On the positive side, it allows several cases to be
attached to a single action, as with the digits in this example. But it also implies that normally
vt
each case must end with a break to prevent falling through to the next. Falling through from one
case to another is not robust, being prone to disintegration when the program is modified. With
the exception of multiple labels for a single computation, fall throughs should be used sparingly,
an d co m m en t ed .
As a matter of good form, put a break after the last case (the default here) even though
it's logically unnecessary. Some day when another case gets added at the end, this bit of
defensive programming will save you.
ternary operator?
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Go to, Loops (For, do-while, while) in C, We have already encountered the while and for
loops. In
while (expression)
statement
in
for (expr1; expr2; expr3)
statement is equivalent to expr1;
while (expr2) {
n.
statement
expr3;
} tio
except for the behaviour of continue, which is described in Section 3.7.
Grammatically, the three components of a forloop are expressions. Most commonly,
expr1and expr3 are assignments or function calls and expr2 is a relational expression.
lu
Any of the three parts can be omitted, although the semicolons must remain. If expr1or
expr3 is omitted, it is simply dropped from the expansion. If the test, expr2, is not present,
it is taken as permanentl y true, so
so
for (;;) {
...
}
u
Whether to use while or for is largely a matter of personal preference. For example, in
while ((c = getchar()) == ' ' || c == '\n' || c = '\t')
; /* skip white space characters */
there is no initialization or re-initialization, so the while is most natural. The for is
preferable when there is a simple initialization and increment since it keeps the loop
control statements close together and visible at the top of the loop. This is most obvious in
for (i = 0; i < n; i++)
...
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
which is the C idiom for processing the first n elements of an array, the analog of the Fortran
DO loop or the Pascal for. The analogy is not perfect, however, since the index variable i
retains its value when the loop terminates for any reason. Because the components of the
forare arbitrary expressions, for loops are not restricted to arithmetic progressions.
Nonetheless, it is bad style to force unrelated computations into the initialization and
increment of a for, which are better reserved for loop control operations.
#include <ctype.h>
/* atoi: convert s to integer; version 2 */
while (expr2) {
statement
in
expr3;
}
n.
except for the behaviour of continue, which is described in Section 3.7.
Grammatically, the three components of a forloop are expressions. Most commonly,
expr1and expr3 are assignments or function calls and expr2 is a relational expression.
tio
Any of the three parts can be omitted, although the semicolons must remain. If expr1or
expr3 is omitted, it is simply dropped from the expansion. If the test, expr2, is not present,
it is taken as permanentl y true, so
for (;;) {
lu
...
}
so
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
for are arbitrary expressions, for loops are not restricted to arithmetic progressions.
Nonetheless, it is bad style to force unrelated computations into the initialization and
increment of a for, which are better reserved for loop control operations.
#include <ctype.h>
/* atoi: convert s to integer; version 2 */
in
for (i = 0; isspace(s[i]); i++) /* skip white space */
;
sign = (s[i] == '-') ? -1 : 1;
n.
if (s[i] == '+' || s[i] == '-') /* skip sign */
i++;
for (n = 0; isdigit(s[i]); i++) tio
n = 10 * n + (s[i] - '0');
return sign * n;
}
lu
The standard library provides a more elaborate function strtolfor conversion of strings to
long integers. The advantages of keeping loop control centralized are even more obvious when
there are several nested loops. The following function is a Shell sort for sorting an array of
so
integers.
The basic idea of this sorting algorithm, which was invented in 1959 by D. L. Shell, is that in
early stages, far-apart elements are compared, rather than adjacent ones as in simpler interchange
sorts. This tends to eliminate large amounts of disorder quickly, so later stages have less work to
u
do. The interval between compared elements is gradually decreased to one, at which point
the sort effectively becomes an adjacent interchange method.
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
v[j] = v[j+gap];
v[j+gap] = temp;
}
}
There are three nested loops. The outermost controls the gap between compared
elements, shrinking it from n/2by a factor of two each pass until it becomes zero. The middle
loop steps along the elements. The innermost loop compares each pair of elements that is
separated by gap and reverses any that are out of order. Since gap is eventually reduced to
one, all elements are eventually ordered correctly. Notice how the generality of the for makes
the outer loop fit in the same form as the others, even though it is not an arithmetic progression.
in
One final C operator is the comma ``,'', which most often finds use in the for statement. A pair of
expressions separated by a comma is evaluated left to right, and the type and value of the result
are the type and value of the right operand. Thus in a for statement, it is possible to
n.
place multiple expressions in the various parts, for example to process two indices in parallel.
This is illustrated in the function reverse(s), which reverses the string sin place.
#include <string.h>
tio
/* reverse: reverse string s in place */
void reverse(char s[])
{
lu
int c, i, j;
for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
so
c = s[i];
s[i] = s[j];
s[j] = c;
}
u
}
vt
The commas that separate function arguments, variables in declarations, etc., are not
comma operators, and do not guarantee left to right evaluation. Comma operators should
be used sparingly. The most suitable uses are for constructs strongly related to each other, as
in the for loop in reverse, and in macros where a multistep computation has to be a single
expression. A comma expression might also be appropriate for the exchange of elements in
reverse, where the exchange can be thought of a single operation:
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Loops - Do-While
The while and for loops test the termination condition at the top. By contrast, the third loop in C,
the do-while, tests at the bottom after making each pass through the loop body; the body
is always executed at least once. The syntax of the do is
do
statement
while (expression);
The statement is executed, then expression is evaluated. If it is true, statement is evaluated again,
in
and so on. When the expression becomes false, the loop terminates. Except for the sense of the
test, do-while is equivalent to the Pascal repeat-until statement. Experience shows that do-while
is much less used than while and for. Nonetheless, from time to time it is valuable, as in the
n.
following function itoa, which converts a number to a character string (the inverse of atoi). The
job is slightly more complicated than might be thought at first, because the easy methods
of generating the digits generate them in the wrong order. We have chosen to generate the
string backwards, then reverse it.
tio
/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
lu
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
so
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
u
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
The do-while is necessary, or at least convenient, since at least one character must be installed
in the array s, even if n is zero. We also used braces around the single statement that makes up
the body of the do-while, even though they are unnecessary, so the hasty reader will not mistake
the while part for the beginning of a while loop.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
It is sometimes convenient to be able to exit from a loop other than by testing at the
top or bottom. The break statement provides an early exit from for, while, and do, just as
from switch. A break causes the innermost enclosing loop or switch to be exited
immediately. The following function, trim, removes trailing blanks, tabs and newlines from
the end of a string, using a breakto exit from a loop when the rightmost non-blank, non-tab,
non newline is found.
/* trim: remove trailing blanks, tabs, newlines */
int n;
in
for (n = strlen(s)-1; n >= 0; n--)
n.
break;
s[n+1] = '\0';
return n;
}
tio
Strlen returns the length of the string. The forloop starts at the end and scans backwards
looking for the first character that is not a blank or tab or newline. The loop is broken when one
is found, or when n becomes negative (that is, when the entire string has been scanned). You
lu
should verify that this is correct behavior even when the string is empty or contains
only white space characters. The continue statement is related to break, but less often used;
it causes the next iteration of the enclosing for, while, or do loop to begin. In the while and do,
so
this means that the test part is executed immediatel y; in the for, control passes to the increment
step. The continue statement applies only to loops, not to switch. A continue inside a switch
inside a loop causes the next loop iteration. As an example, this fragment processes only the non-
negative elements in the array a; negative values are skipped.
continue;
The continue statement is often used when the part of the loop that follows is complicated,
so that reversing a test and indenting another level would nest the program too deeply.
Go to and labels
C provides the infinitely-abusable goto statement, and labels to branch to. Formally, the
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
goto statement is never necessar y, and in practice it is almost always easy to write code
without it.
Nevertheless, there are a few situations where gotos may find a place. The most common is
to abandon processing in some deeply nested structure, such as breaking out of two or more
loops at once. The break statement cannot be used directly since it only exits from the
innermost loop.
Thus:
for ( ... ) {
...
if (disaster)
in
goto error;
}
n.
...
error:
if (a[i] == b[j])
goto found;
/* didn't find any common element */
u
...
found:
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
found = 1;
if (found)
/* got one: a[i-1] == b[j-1] */
...
else
/* didn't find any common element */
With a few exceptions like those cited here, code that relies on goto statements is
generally harder to understand and to maintain than code without gotos. Although we are not
dogmatic about the matter, it does seem that goto statements should be used rarely, if at all.
in
n.
tio
lu
u so
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
MODULE III
in
brackets
after the array name.
E x am p l e,
n.
M ark s [7 ]
Represents the marks of the 7th student. The complete set of values is referred to as an
array, the
tio
individual values are called elements. The arrays can be of any variable type.
One-dimensional array:
lu
When a list of items can be given one variable name using only one subscript
and such a
so
The subscripted variable xi refers to the ith element of x. The subscript can begin with
number 0.
vt
Num[0]
Num[1]
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Num[2]
Num[3]
Num[4]
in
Num[3]=17;
Num[4]=23;
The table below shows the values that are stored in the particular numbers.
n.
Num[0] 57
Num[1] 20
Num[2] 56 tio
Num[3] 17
Num[4] 23
lu
Two dimensional arrays:
There are certain situations where a table of values will have to be stored. C allows us to
define such table using two dimensional arrays.
so
Two dimensional arra ys are stored in memory as shown in the table below. Each dimension of
the array is indexed from zero to its maximum size minus one; the first index selects the row and
vt
Column0 Co l u mn 1 Column2
[0 ][0 ] [0][1] [0 ][2 ]
Ro w 0 210 340 560
[1 ][0 ] [1][1] [1 ][2 ]
Ro w 1 380 290 321
[2 ][0 ] [2][1] [2 ][2 ]
Row2 490 235 240
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
E x am p l e:
Float weight[40]
Declares the weight to be an array containing 40 real elements. Any subscripts 0 to 39
n.
are valid.
Similarly,
Int group1[11];
tio
Decalres the group1 as an array to contain a maximum of 10 integer constants.
The C language treats character strings simply as arra ys of characters. The size in a
character
string represents the maximum number of characters that the string can hold.
lu
For example:
Char text[10];
so
Suppose we read the following string constant into the string variable text.
“HOW ARE YOU”
Each character of the string is treated as an element of the array text and is stored in the
memory
u
as follows.
‘H’
vt
‘O’
‘W’
‘A’
‘R ’
‘E’
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
The values in the list are separated by commas.
For example, the statement below shows
Static int num[3]={2,2,2};
n.
Will declare the variable num as an array of size 3 and will assign two to each element. If
the number of values is less than the number of elements, then only that many elements
will be initialized. The remaining elements will be set to zero automatically.
For example: tio
Static float num1[5]={0.1,2.3,4.5};
Will initialize the first three elements to 0.1,2.3 and 4.5 and the remaining two elements to
zero.
lu
The word static used before type declaration declares the variable as a static variable.
In some cases the size may be omitted. In such cases, the compiler allocates enough space for
all initialized elements. For example, the statement
so
Declares the name to be an array of four characters, initialized with the string “SWAN”
There certain draw backs in initialization of arrays.
vt
#include<stdio.h>
m a i n ()
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
{
int a[10][10];
int i, j row,col;
printf(“\n Input row and column of a matrix:”);
scanf(“%d %d”, &row,&col);
for(i=0; i<row;i++)
for(j=0;j<col;j++)
scanf(“%d”, &a[i][j]);
for(i=0;i<row;i++)
in
{
for(j=0;j<col;j++)
printf(“%5d”, a[i][j]);
n.
printf(“\n”);
}
tio
Program showing one-dimensional array
m a i n ()
lu
{
int i;
so
float a[10],value1,total;
printf(“Enter 10 Real numbers\n”);
for(i=0;i<10;i++)
u
{
scanf(“%f”, &value);
vt
x[i]=value1;
}
total=0.0;
for(i=0;i<10;i++)
total=total+a[i]*a[i];
printf(“\n”);
for(i=0;i<10;i++)
printf(“x[%2d]= %5.2f\n”, i+1, x[i]);
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
printf(“\ntotal=%.2f\n”, total);
}
Programming examples:
#define R1 4
#define C1 4
m a i n ()
in
{
int row,col,prod[R1][C1];
n.
int i,j;
printf(“ MULTIPLICATION TABLE \n\n”);
printf(“ “);
for(j=1;j<=C1;j++)
printf(“%4d”,j);
tio
printf(“\n”);
lu
printf(“-------------------------------------------\n”);
for(i=0;i<R1;i++)
so
{
row=i+1;
printf(“%2d|”, R1);
for(j=1;j<=C1;j++)
u
{
col=j;
vt
prod[i][j]=row*col;
printf(“%4d”, prod[i][j]);
}
printf(“\n”);
}
}
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Output:
MULTIPLICATION TABLE
1 2 3 4
-------- ----- ------ ------ ----- -------- -
1 | 1 2 3 4
2 | 2 4 6 8
3 | 3 6 9 12
4 | 4 8 12 16
S T RI N G S
in
String variable:
A string is an array of characters. Any group of characters defined
between
n.
double quotation marks is called a constant string.
E x am p l e:
“Good Morning Everybody” tio
Character strings are often used to build meaningful and readable programs.
A string variable is any valid C variable name and is always declared as an array.
lu
Declaring and initializing string variables:
The general form of string variable is
char string_name[size];
so
character(‘\0’) at the end of the string. Character arrays may be initialized when
they are
declared. C permits a character array to be initialized in either of the following two
forms:
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
To read a string of characters input function scanf can be used with %s format
specification.
in
E x am p l e:
ch ar ad d [2 0 ];
n.
Scanf(“%s”, add);
Note that unlike previous scanf calls, in the case of character arrays, the &(ampersand) is not
tio
required before the variable name. The scanf function automatically terminates the string that
is read with a null character and therefore the character array should be large enough to hold
the input string plus the null character. Program to read a series of words using scanf function
lu
m a i n ()
{
char text1[50],text2[50],text3[50],text4[50];
so
printf(“Enter text:\n”);
scanf(“%s %s”, text1,text2);
scanf(“%s”, text3);
u
scanf(“%s”, text4);
printf(“\n”);
vt
Writing strings:
The printf function with %s can be used to display an array of characters that is
terminated by the null character.
E x am p l e:
printf(“%s”, text);
Dept. of ISE, vtusolution.in Page 57
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Can be used to display the entire contents of the array name. We can also specify the precision
with which the array is displayed. For example, the specification
%12.4
indicates that the first four characters are to printed in a field width of 12 columns.
in
static char state[15]= “MADHYA PRADESH”;
printf(“\n \n”);
printf(“----------------------------------\n”);
n.
printf(“%13s\n”, state);
printf(“%5s\n”, state);
printf(“%15.6s \n”, state); tio
printf(“%15.0s\n”, state);
printf(“%.3s\n”, state);
}
lu
String functions:
C library supports a large number of string functions. The list given below depicts the
string
so
functions
Function Action
strcat() concatenates two strings
strcmp() compares two strings
u
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
E x am p l e:
Text1= VERY \0
Text2= GOOD\0
Text3= BAD\0
Strcat(text1,text2);
Text1= VERY GOOD\0
Text2= GOOD\0
Strcat(text1,text3);
in
Text1= VERY BAD
T ex t 2 = BA D
We must make sure that the size of string1 is large enough to accommodate the final
n.
string. Strcat function may also append a string constant to string variable.
For example:
strcat(text1,”GOOD”); tio
C permits nesting of strcat functions. The statement
strcat(strcat(string1,string2),string3);
lu
Is allowed and concatenates all the three strings together. The resultant string is stored
in
string1.
so
strcmp(string1,string2);
vt
strcmp(name1,name2);
strcmp(name1, “ABHI”);
strcmp(“ROM”, “RAM”);
We have to determine whether the strings are equal, if not which is alphabetically above.
String copying/strcpy() function:
The strcpy() function works almost like a string-assignment operator. The general format
Dept. of ISE, vtusolution.in Page 59
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
is
strcpy(string1,string2);
Will assign the string “BANGALORE” to the string variable city. The statement
strcpy(city1,city2); will assign the contents of the string variable city2 to the string
variable city1. The size of the array city1 should be large enough to receive the contents
of city2.
in
Finding the length of a string/strlen();
This function counts and returns the number of characters in a string.
n.
The general syntax is n=strlen(string);
Where n is an integer variable which receives the value of the length of the string.
The argument may be a string constant. The counting ends at the first null charact er.
tio
Implementing the above functions without using string functions:
String concatenation:
We cannot assign one string to another directly,we cannot join two strings together by
the simple arithmetic addition. The characters from string1 and string2 should be copied into
lu
the string3 one after the other. The size of the array string3 should be large enough to hold the
total characters.
main()
{
int i,j,k;
u
for(i=0;first_name[i]!=’\0’;i++)
name[i]=first_name;
for(i=0;second_name[j]!=’\0’; j++)
name[i+j+1]=sec_name[j];
name[i+j+1] =’ ‘;
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
for(k=0;last_name[k]!=’\0’;k++)
name[i+j+k+2]=last_name[k];
name[i+j+k+2]=’\0’;
printf(“\n \n”);
printf(“%s \n”, name);
}
Output
ATAL RAM KRISHNA
String comparison:
in
Comparison of two strings cannot be compared directly. It is therefore necessary
to
n.
compare the strings to be tested, character by character. The comparison is done until
there is a
mismatch or one of the strings terminates into a null character.
tio
The following segment of a program illustrates this,
i=i+1;
if(str1[i]==’\0’ && str2[i]==’\0’)
printf(“strings are equal\n”);
u
else
printf(“strings are not equal\n”);
vt
main()
{
char string1[80],string2[80];
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
int j;
printf(“Enter a string\n”);
printf(“?”);
scanf(“%s”, string2);
for(j=0;string2[i]!=’\0’;j++)
string1[j]=string2[j];
string1[j]=’\0’;
printf(“\n”);
printf(“%s\n”,string1);
in
printf(“Number of characters=%d\n”, j);
}
Program to find the length of a string:
n.
#include<stdio.h>
main() tio
{ char line[80],character
int c=0,i;
printf(“Enter the text\n”);
lu
for(i=0;line[i];!=’\0’;i++)
{ character=getchar();
line[i]=character;
so
c++;
}
printf(“The length of the string \n”, c);
u
}
vt
ex am p l e:
y=’a’;
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
printf(“%d\n”, y);
will display the number 97 on the screen.
For example:
y=’z’-1;
Is a valid statement. In ASC II , the value of ‘z’ is 122 and therefore , the statement
will assign the value 121 to the variable Y. We may also use character constants in
relational expressions.
in
For example:
Would test whether the character contained in the variable ch is an lower-case letter.
n.
We can convert a character digit to its equivalent integer value using the following
relationship :
y=character –‘0’;
tio
Where y is defined as an integer variable and character contains the character digit.
Example: Let us assume that the character contains the digit ‘7’, then,
y=ASCII value of ‘7’-ASCII value of ‘0’
lu
= 55-48
=7
so
C library has a function that converts a string of digits into their integer values. The
function takes the form
y=atoi(string);
y is an integer variable and string is a character array containing a string or digits
u
y e a r= a t o i (n u m );
Num is a string variable which is assigned the string constant “1974”. The
function atoi converts the string “1974” to its numeric equivalent 1974 and assigns it
to the integer variable year.
Programming examples:
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
#define MAX 25
m a i n ()
{
char str [ITEMS][MAX], dum[MAX];
int i=0;j=0;
printf(“Enter names of %d items \n”, ITEMS);
while(i<ITEMS)
scanf(“%s”, str[i++]);
for(i=1;i<ITEMS;i++)
in
{
for(j=1;j<=ITEMS-i;j++)
{
n.
if(strcmp(string[j-1],string[j])>0)
strcpy(dummy,string[j-1]);
strcpy(str[j-1],str[j]);
tio
strcpy(str[j],dummy);
}
}
lu
for(i=0;i<ITEMS;i++)
printf(“%s”, str[i]);
}
so
{
char s1[20],s2[20],s3[20];
vt
int y,len1,len2,len3;
printf(“\n Enter two string constants\n”);
printf(“?”);
scanf(“%s %s”, s1,s2);
x=strcmp(s1,s2);
If(y!=0)
{
printf(“\n\n Strings are not equal\n”);
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
strcat(s1,s2);
}
else
printf(“\n\n Strings are equal\n”);
strcpy(s3,s1);
len1=strlen(s1);
len2=strlen(s2);
len3=strlen(s3);
printf(“\n s1= %s length= %d character \n”,s1,len1);
in
printf(“\n s1= %s length= %d character \n”,s2,len2);
printf(“\n s1= %s length= %d character \n”,s3,len3);
}
n.
Program to convert lowercase characters in to upper case characters:
#include<stdio.h>
main() tio
{
ch a r t ex t [8 5 ];
int i=0;
lu
printf(“Enter a line of text in lowercase:\t”);
scanf(“%[^\n]”,text);
printf(“%s”,text);
so
i++;
}
vt
printf(“\n”);
}
Functions break large computing tasks into smaller ones, and enable people to build on
what others have done instead of starting over from scratch. Appropriate functions hide
details of operation from parts of the program that don't need to know about them, thus
clarifying the whole, and easing the pain of making changes. C has been designed to make
functions efficient and easy to use; C programs generally consist of many small functions
rather than a few big ones. A program may reside in one or more source files. Source files
may be compiled separately and loaded together, along with previously compiled functions
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
from libraries. We will not go into that process here, however, since the details vary
from s ystem to system. Function declaration and definition is the area where the ANSI
standard has made the most changes to C. Possible to declare the type of arguments when
a function is declared. The syntax of function declaration also changes, so that declarations
and definitions match. This makes it possible for a compiler to detect many more errors
than it could before. Furthermore, when arguments are properly declared, appropriate type
coercions are performed automatically. The standard clarifies the rules on the scope of names;
in particular, it requires that there be only one definition of each external object.
Initialization is more general: automatic arrays and structures may now be initialized.
The C preprocessor has also been enhanced. New preprocessor facilities include a more
complete set of conditional compilation directives, a way to create quoted strings from
macro arguments, and better control over the macro expansion process. To begin with, let
in
us design and write a program to print each line of its input that contains a particular
``pattern'' or string of characters. (This is a special case of the UNIX program grep.) For
example, searching for the pattern of letters ``ould'' in the set of lines.
n.
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
int getline(char line[], int max) tio
int strindex(char source[], char searchfor[]);
char pattern[] = "ould"; /* pattern to search for */
/* find all lines matching pattern */
lu
m a i n ()
{
char line[MAXLINE];
so
int found = 0;
while (getline(line, MAXLINE) > 0)
if (strindex(line, pattern) >= 0) {
u
printf("%s", line);
found++;
vt
}
return found;
}
/* getline: get line into s, return length */
int getline(char s[], int lim)
{
int c, i;
i = 0;
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++) {
n.
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++)
;
if (k > 0 && t[k] == '\0') tio
re t u rn i ;
}
return -1;
lu
}
Each function definition has the form return-type function-name(argument declarations)
{
so
returns nothing. A do-nothing function like this is sometimes useful as a place holder
during program development. If the return type is omitted, int is assumed.
vt
The functions can occur in any order in the source file, and the source program can be split
into multiple files, so long as no function is split. The return statement is the mechanism for
returning a value from the called function to its caller. Any expression can follow
return: return expression;
The expression will be converted to the return type of the function if necessary. Parentheses
Dept. of ISE, vtusolution.in Page 67
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
are often used around the expression, but they are optional. The calling function is free to
ignore the returned value. Furthermore, there need to be no expression after return; in that
case, no value is returned to the caller. Control also returns to the caller with no value when
execution ``falls off the end'' of the function by reaching the closing right brace. It is not
illegal, but probably a sign of trouble, if a function returns a value from one place and no
value from another. In any case, if a function fails to return a value, its ``value'' is certain
to be garbage. The pattern-searching program returns a status from main, the number of
matches found. This value is available for use by the environment that called the program.
in
First, atofitself must declare the t ype of value it returns, since it is not int. The type
name
precedes the function name:
n.
#include <ctype.h>
/* atof: convert string s to double */
double atof(char s[])
{
double val, power;
tio
int i, sign;
lu
for (i = 0; isspace(s[i]); i++) /* skip white space */
;
sign = (s[i] == '-') ? -1 : 1;
so
i++;
for (power = 1.0; isdigit(s[i]); i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10;
}
return sign * val / power;
}
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Second, and just as important, the calling routine must know that atofreturns a non-int value.
One way to ensure this is to declare atof explicitly in the calling routine. The declaration is
shown in this primitive calculator (barely adequate for check-book balancing), which reads
one number per line, optionally preceded with a sign, and adds them up, printing the
running sum after each input:
#include <stdio.h>
/* rudimentary calculator */
main()
in
{
n.
int getline(char line[], int max);
sum = 0;
tio
while (getline(line, MAXLINE) > 0)
printf("\t%g\n", sum += atof(line));
return 0;
lu
}
The declaration
double sum, atof(char []); says that sum is a double variable, and that atof is a function that
so
takes one char[]argument and returns a double. The function atof must be declared
and defined consistently. If atof itself and the call to it in main have inconsistent types in the
same source file, the error will be detected by the compiler. But if (as is more likel y)
atof were compiled separately, the mismatch would not be detected, atof would return a
u
double that main would treat as an int, and meaningless answers would result.
In the light of what we have said about how declarations must match definitions, this might
vt
seem surprising. The reason a mismatch can happen is that if there is no function prototype, a
function is implicitly declared by its first appearance in an expression, such as
sum += atof(line)
If a name that has not been previously declared occurs in an expression and is followed by a
left parentheses, it is declared by context to be a function name, the function is assumed to
return an int, and nothing is assumed about its arguments. Furthermore, if a function
declaration does not include arguments, as in.
The structure of the program is thus a loop that performs the proper operation on each
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
push result
in
else if (newline)
n.
else
error
tio
The operation of pushing and popping a stack are trivial, but by the time error detection
and recovery are added, they are long enough that it is better to put each in a separate function
than to repeat the code throughout the whole program. And there should be a separate
function for fetching the next input operator or operand. The main design decision that
lu
has not yet been discussed is where the stack is, that is, which routines access it directly. On
possibility is to keep it in main, and pass the stack and the current stack position to the
routines that push and pop it.
so
But main doesn't need to know about the variables that control the stack; it only does push
and pop operations. So we have decided to store the stack and its associated information in
external variables accessible to the push and pop functions but not to main. Translating this
u
outline into code is easy enough. If for now we think of the program as existing in one
source file, it will look like this:
vt
#includes
#defines
main() { ... }
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Later we will discuss how this might be split into two or more source files. The function
main is a loop containing a big switch on the type of operator or operand; this is a more
t ypical use of switch than the one
#include <stdio.h>
in
#define MAXOP 100 /* max size of operand or operator */
n.
int getop(char []);
void push(double);
double pop(void); tio
/* reverse Polish calculator */
main()
{
lu
int type;
double op2;
so
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
u
push(atof(s));
break;
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
case '\n': printf("\t%.8g\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
in
break;
}
}
n.
re t u rn 0 ;
}
tio
#define MAXVAL 100 /* maximum depth of val stack */
int sp = 0; /* next free stack position */
double val[MAXVAL]; /* value stack */
lu
/* push: push f onto value stack */
void push(double f)
{
so
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
}
}
A variable is external if it is defined outside of any function. Thus the stack and stack index
that must be shared by push and pop are defined outside these functions. But main itself
does not refer to the stack or stack position - the representation can be hidden. Let us
now turn to the implementation of getop, the function that fetches the next operator or
operand. The task is easy.
Skip blanks and tabs. If the next character is not a digit or a hexadecimal point, return
it, Otherwise, collect a string of digits (which might include a decimal point), and return
in
NUMBER, the signal that a number has been collected.
#include <ctype.h>
n.
int getch(void);
tio
Because +and *are commutative operators, the order in which the popped operands are
combined is irrelevant, but for -and /the left and right operand must be distinguished.
In push(pop() - pop()); /* WRONG */ the order in which the two calls of pop are evaluated
lu
is not defined. To guarantee the right order, it is necessary to pop the first value into a
temporar y variable as we did in main.
so
void ungetch(int);
int i, c;
s[1] = '\0';
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
i = 0;
in
;
s[i] = '\0';
n.
i f (c != E O F)
ungetch(c);
return NUMBER;
}
tio
What are getchand ungetch? It is often the case that a program cannot determine that it has
read enough input until it has read too much. One instance is collecting characters that
make up a number: until the first non-digit is seen, the number is not complete. But then
lu
the program has read one character too far, a character that it is not prepared for.
The problem would be solved if it were possible to ``un-read'' the unwanted character.
so
Then, every time the program reads one character too many, it could push it back on the
input, so the rest of the code could behave as if it had never been read. Fortunately, it's
easy to simulate ungetting a character, by writing a pair of cooperating functions.
getchdelivers the next input character to be considered; ungetch will return them before
u
reading new i nput. How they work together is simple. ungetchputs the pushed-back
vt
characters into a shared buffer -- a character array. getchreads from the buffer if there is
anything else, and calls getcharif the buffer is empty.
There must also be an index variable that records the position of the current character in
the buffer. Since the buffer and the index are shared by getchand ungetchand must retain their
values between calls, they must be external to both routines. Thus we can write getch,
ungetch, and their shared variables as:
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
if (bufp >= BUFSIZE)
n.
else
buf[bufp++] = c;}
Static Variables tio
The variables spand valin stack.c, and buf and bufpin getch.c, are for the private use
of the functions in their respective source files, and are not meant to be accessed by
lu
anything else.
The static declaration, applied to an external variable or function, limits the scope of that
object to the rest of the source file being compiled. External static thus provides a way to
so
hide names like buf and bufpin the getch ungetch combination, which must be external
so they can be shared, yet which should not be visible to users of getch and ungetch. Static
storage is specified by prefixing the normal declaration with the word static. If the two
u
then no other routine will be able to access bufand bufp, and those names will not conflict
with the same names in other files of the same program. In the same way, the variables that
push and pop use for stack manipulation can be hidden, by declaring sp and valto be static.
The external static declaration is most often used for variables, but it can be applied to
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
functions as well. Normally, function names are global, visible to any part of the entire
program. If a function is declared static, however, its name is invisible outside of the file in
which it is declared.
The static declaration can also be applied to internal variables. Internal static variables are
local to a particular function just as automatic variables are, but unlike automatics, they
remain in existence rather than coming and going each time the function is activated.
This means that internal static variables provide private, permanent storage within a single
function.
Register Variables
in
A register declaration advises the compiler that the variable in question will be
heavil y used. The idea is that register variables are to be placed in machine registers, which
n.
may result in smaller and faster programs. But compilers are free to ignore the advice. The
register declaration looks like
and so on. The registerdeclaration can only be applied to automatic variables and to the
lu
formal parameters of a function. In this later case, it looks like
register int i;
...
u
}
vt
Initialization has been mentioned in passing many times so far, but always peripherally to
some other topic. This section summarizes some of the rules, now that we have discussed
the various storage classes. In the absence of explicit initialization, external and static
variables are guaranteed to be initialized to zero; automatic andregister variables have
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Scalar variables may be initialized when they are defined, by following the name with an
equals sign and an expression:
int x = 1;
in
For external and static variables, the initializer must be a constant expression; the
initialization is done once, conceptionally before the program begins execution. For
automatic and register variables, the initializer is not restricted to being a constant: it may
n.
be any expression involving previously defined values, even function calls.
{
tio
int low = 0;
lu
int high = n - 1;
int mid;
so
...
instead of
u
low = 0;
high = n - 1;
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
When the size of the array is omitted, the compiler will compute the length by counting
the initializers, of which there are 12 in this case. If there are fewer initializers for an array
than the specified size, the others will be zero for external, static and automatic variables. It
is an error to have too many initializers. There is no way to specify repetition of an
initializer, nor to initialize an element in the middle of an array without supplying all
in
the preceding values as well.
Character arrays are a special case of initialization; a string may be used instead of the
n.
braces and commas notation:
char pattern[] = { 'o', 'u', 'l', 'd', '\0' }; In this case, the array size is five (four characters plus
lu
the terminating '\0').
u so
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
MO D U L E - I V
Array is used to represent a group of data items that belongs to same data-type, such as int
or float. However, if we want to represent a collection of data items of different data-types
using a single name, then we cannot use an array. For that C supports constructed data
type known as structure.
in
“A structure is a used-defined data t ype, which contains group of multiple different data
type related variable.”
n.
We can define the structure by following format:
struct tag_name {
datatype element_1;
datatype element_2;
tio
…
lu
datatype element_n;
};
so
In above syntax, ‘struct’ keyword declares a structure holds multiple different data type
variable.
u
These variables are known as the structure elements or members of structure. Each
vt
member may have same or different data type. The name of the structure is known as
tagname. In above format there is no any declaration is made but it defines only the format of
structure variable so it is known as structure template. Structure variable can be declared as
following way:
c h a r n a m e [1 0 0 ] ;
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
char address[100];
};
It is also allows both structure declaration and template creation in one statement:
struct tag_name {
datatype m em b er_ 1 ;
in
datatype m em b er_ 2 ;
datatype m em b er_ 3 ;
n.
…
datatype m em b er_ n ;
}
tio
variable_1, variable_2, variable_3;
Here both the task, one is structure template definition and variable declaration is made in
lu
one statement. ‘variable_1’, ‘variable_2’, ‘variable_3’ are structure variable after declaration.
We can define structure out of any function or inside function. When we define structure
out of any function the structure definition is global and can be used by any other function.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
int rollno;
c h a r n a m e [1 0 0 ] ;
char address[100];
};
in
m ai n ( ) {
s1.rollno = 1;
n.
strcpy (s1.name, “Shantilal”);
}
tio
Here we have assign the rollno, name, and address of student by using dot operator. Similarly
we can read structure elements and print it.
lu
scanf(“ %d”, &s1.rollno);
scnaf(“ %s”, s1.name);
so
Initialization of structure: -
We can initialize structure as like as array by specifying list of values in curly bracket.
vt
int rollno;
c h a r n a m e [1 0 0 ] ;
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
char address[100];
};
m ai n ( ) {
struct student s1={1,”Shantilal”, “Ahmedabad” }; // Initialization
In above example we have initialized the structure elements by separating with comma in
curly bracket. We assigned values 1, Shantilal, Ahmedabad to rollno, name, and address
in
respectively.
n.
e.g. struct student {
} tio
ANSI C standard allows the initialization of auto storage class variable but non ANSI
compiler allows only initialization of static and extern storage class variable. So for that
we must write static or extern before declaration.
lu
static struct variable_1= { list of values separated by comma };
Array of Structure
u
As we known that structure is a group of related different data t ype variables. Sometimes
we need multiple variables of structure for that we can use the array of structure. For
vt
example we have structure of student. We want the list of students of entire class but the
one variable of structure can represent only one student. So to represent entire class
variable we have to use array of student structure.
We can declare the array of structure as simply as other data type array. And same way to
other data type we can use this variable with the subscript.
struct arrayname[size];
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
int rollno;
c h a r n a m e [1 0 0 ] ;
char address[100];
};
m ai n ( ) {
struct student s[10];
in
int i;
n.
for(i=0 ; i < 10 ; i ++) {
scanf(“%d”, &s[i].rollno);
scanf(“%s”, s[i].name);
scanf(“%s”, s[i].address);
tio
}
lu
}
so
We can initialize the array of structure as like as the two dimensional array:
Object conepts was derived from Structure concept. You can achieve few object oriented
goals using C structure but it is very complex.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
struct student {
char firstName[20];
char lastName[20];
c h a r S S N [9 ] ;
float gpa;
};
Now you have a new datatype called student and you can use this datatype define your
in
variables of student type:
struct student student_a, student_b; or an array of students as
n.
struct student students[50];
struct {
tio
char firstName[20];
lu
char lastName[20];
c h a r S S N [1 0 ] ;
so
float gpa;
} student_a, student_b;
variables.
SSN : 2333234
GPA : 2009.20
Type Definition
There is an easier way to define structs or you could "alias" types you create. For example:
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
typedef struct{
char firstName[20];
char lastName[20];
char SSN[10];
float gpa;
}student;
Now you can use student directly to define variables of student type without using
in
struct keyword. Following is the example:
student student_a;
n.
You can use typedef for non-structs:
pint32 x, y, z;
tio
x, y and z are all pointers to long ints.
lu
Defining Opening and Closing of files
When accessing files through C, the first necessity is to have a way to access the files. For C
File I/O you need to use a FILE pointer, which will let the program keep track of the
so
FIL E * f p ;
u
To open a file you need to use the fopen function, which returns a F ILE pointer. Once
you've opened a file, you can use the FILE pointer to let the compiler perform input
vt
Here filename is string literal which you will use to name your file and mode can have one of
the following values
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Note that it's possible for fopen to fail even if your program is perfectly correct: you might
try to open a file specified by the user, and that file might not exist (or it might be write-
protected). In those cases, fopen will return 0, the NULL pointer.
FIL E * f p ;
in
fp=fopen("/home/tutorialspoint/test.txt", "r");
n.
This code will open test.txt for reading in text mode. To open a file in a binary mode you
must add a b to the end of the mode string; for example, "rb" (for the reading and writing
modes, you can add the b either after the plus sign - "r+b" - or before - "rb+")
tio
To close a function you can use the function:
fclose(fp);
To work with text input and output, you use fprintf and fscanf, both of which are similar to
their friends printf and scanf except that you must pass the FILE pointer as first argument.
u
#include <stdio.h>
vt
m a i n ()
FIL E * f p ;
fp = fopen("/tmp/test.txt", "w");
fclose(fp;);
Dept. of ISE, vtusolution.in Page 86
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
This will create a file test.txt in /tmp directory and will write This is testing in that file.
#include <stdio.h>
m a i n ()
FIL E * f p ;
in
c h a r b u ff e r [ 2 0 ] ;
fp = fopen("/tmp/test.txt", "r");
n.
fscanf(fp, "%s", buffer);
}
fclose(fp;);
tio
It is also possible to read (or write) a single character at a time--this can be useful if you
lu
wish to perform character-by-character input. The fgetc function, which takes a file pointer,
and returns an int, will let you read a single character from a file:
so
The fgetc returns an int. What this actually means is that when it reads a normal character in
the file, it will return a value suitable for storing in an unsigned char (basically, a number
u
in the range 0 to 255). On the other hand, when you're at the very end of the file, you
can't get a character value--in this case, fgetc will return "EOF", which is a constnat that
vt
The fputc function allows you to write a character at a time-- you might find this useful if
you wanted to copy a file character by character. It looks like this:
Note that the first argument should be in the range of an unsigned char so that it is a
valid character. The second argument is the file to write to. On success, fputc will return the
value c, and on failure, it will return EOF.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Binary I/O
There are following two functions which will be used for binary input and output:
in
n.
Both of these functions deal with blocks of memories - usually arrays. Because they
accept pointers, you can also use these functions with other data structures; you can even write
structs to a file or a read struct into memory.
Output: In any programming language output means to display some data on screen, printer
or in any file. C programming language provides a set of built-in functions to output required
data.
Here we will discuss only one input function and one putput function just to understand
u
the meaning of input and output. Rest of the functions are given into C - Built-in Functions
vt
printf() function
This is one of the most frequently used functions in C for output. ( we will discuss
what is function in subsequent chapter. ).
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
5 abc 3.140000 c
Here %d is being used to print an integer, %s is being usedto print a string, %f is being
used to print a float and %c is being used to print a character.
in
A complete syntax of printf() function is given in C - Built-in Functions
n.
scanf() function
This is the function which can be used to to read an input from the command line.
tio
lu
u so
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
MODULE V
Let's start learning them in simple and easy steps. As you know, every variable is a
memor y location and every memory location has its address defined which can be
accessed using ampersand (&) operator, which denotes an address in memory. Consider the
in
following example, which will print the address of the variables defined:
#include <stdio.h>
n.
int main ()
int var1;
ch ar v ar2 [1 0 ];
tio
printf("Address of var1 variable: %x\n", &var1 );
lu
printf("Address of var2 variable: %x\n", &var2 );
re t u rn 0 ;
so
}
u
When the above code is compiled and executed, it produces result something as follows:
So you understood what is memory address and how to access it, so base of the concept is
over.
A pointer is a variable whose value is the address of another variable, i.e., direct address of
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
the memory location. Like any variable or constant, you must declare a pointer before you
can use it to store any variable address. The general form of a pointer variable declaration is:
t y p e * v a r-n a m e ;
Here, t ype is the pointer's base type; it must be a valid C data t ype and var-name is the
name o f the pointer variable. The asterisk * you used to declare a pointer is the same asterisk
that you use for multiplication. However, in this statement the asterisk is being used to
designate a variable as a pointer. Following are the valid pointer declaration:
in
double *dp; /* pointer to a double */
n.
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or
tio
otherwise, is the same, a long hexadecimal number that represents a memory address. The
only difference between pointers of different data types is the data type of the variable
or constant that the pointer points to.
(c) finall y access the value at the address available in the pointer variable. This is done
u
by using unar y operator * that returns the value of the variable located at the address
vt
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
n.
NULL Pointers in C
It is always a good practice to assign a NULL value to a pointer variable in case you do not
have exact address to be assigned. This is done at the time of variable declaration. A
tio
pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard
libraries.
lu
Consider the following program:
#include <stdio.h>
so
int main ()
{
u
return 0;
When the above code is compiled and executed, it produces the following result:
T h e v al u e o f p t r i s 0
On most of the operating s ystems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating s ystem. However, the memory
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
address 0 has special significance; it signals that the pointer is not intended to point to an
accessible memor y location. But by convention, if a pointer contains the null (zero) value, it
is assumed to point to nothing.
C Pointers in Detail:
Pointers have many but easy concepts and they are very important to C programming. There
in
are following few important pointer concepts which should be clear to a C programmer:
Co n cep t Description
n.
C - Pointer arithmetic There are four arithmetic operators that can be used on pointers: ++, --
, +, -
tio
C - Array of pointers You can define arrays to hold a number of pointers.
One of the best things about pointers is that they allow functions to alter variables outside
of there own scope. By passing a pointer to a function you can allow that function to
vt
read and write to the data stored in that variable. Say you want to write a function that swaps
the values of two variables. Without pointers this would be practically impossible, here's
how you do it with pointers:
Example swap_ints.c
#include <stdio.h>
int
Dept. of ISE, vtusolution.in Page 93
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
m a i n ()
{
int a = 4, b = 7;
printf("pre-swap values are: a == %d, b == %d\n", a, b)
swap_ints(&a, &b);
re t u rn 0 ;
}
int
in
swap_ints(int *first_number, int *second_number)
{
int temp;
n.
/* temp = "what is pointed to by" first_number; etc... */
temp = *first_number;
*first_number = *second_number;
*second_number = temp;
}
re t u rn 0 ;
tio
As you can see, the function declaration of swap_ints() tells GCC to expect two
lu
pointers (address of variables). Also, the address-of operator (&) is used to pass the address
of the two variables rather than their values. swap_ints() then reads
so
write to the data stored in that variable. Say you want to write a function that swaps the values of
two variables. Without pointers this would be practically impossible, here's how you do it with
vt
pointers:
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
int a = 4, b = 7;
printf("pre-swap values are: a == %d, b == %d\n", a, b)
swap_ints(&a, &b);
printf("post-swap values are: a == %d, b == %d\n", a, b)
re t u rn 0 ;
}
Int swap_ints(int *first_number, int *second_number)
{
int temp;
in
/* temp = "what is pointed to by" first_number; etc... */
temp = *first_number;
*first_number = *second_number;
n.
*second_number = temp;
re t u rn 0 ; }
tio
As you can see, the function declaration of swap_ints() tells GCC to expect two
pointers (address of variables). Also, the address-of operator (&) is used to pass the
address of the two variables rather than their values. swap_ints() then reads
lu
Address Arithmetic
C pointer is an address, which is a numeric value. Therefore, you can perform
so
arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic
operators that can be used on pointers: ++, --, +, and - .
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to
u
the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation
on the pointer:
vt
ptr++
Now, after the above operation, the ptr will point to the location 1004 because each time
ptr is incremented, it will point to the next integer location which is 4 bytes next to
the current location. This operation will move the pointer to next memory location without
impacting actual value at the memory location. If ptr points to a character whose address
is 1000, then above operation will point to the location 1001 because next character will be
available at 1001.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can
be incremented, unlike the array name which cannot be incremented because it is a constant
pointer.
The following program increments the variable pointer to access each succeeding element of
the array:
#include <stdio.h>
const int MAX = 3;
in
int main ()
{
int var[] = {10, 100, 200};
n.
int i, *ptr;
/* let us have array address in pointer */
ptr = var; tio
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %x\n", i, ptr );
lu
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
so
}
re t u rn 0 ;
}
u
When the above code is compiled and executed, it produces result something as follows:
Address of var[0] = bf882b30
vt
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by
the number of bytes of its data type as shown below:
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--)
in
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
n.
/* move to the previous location */
ptr--;
} tio
re t u rn 0 ;
}
When the above code is compiled and executed, it produces result something as follows:
lu
Address of var[3] = bfedbcd8
Value of var[3] = 200
Address of var[2] = bfedbcd4
so
Pointer Comparisons
vt
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2
point to variables that are related to each other, such as elements of the same array, then p1
and p2 can be meaningfully compared.
The following program modifies the previous example one by incrementing the variable
pointer so long as the address to which it points is either less than or equal to the address
of the last element of the array, which is &var[MAX - 1]:
#include <stdio.h>
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
in
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
n.
/* point to the previous location */
ptr++;
i++; tio
}
re t u rn 0 ;
}
lu
When the above code is compiled and executed, it produces result something as follows:
Value of var[0] = 10
Address of var[1] = bfdbcb24
Value of var[1] = 100
u
As a developer, you should understand the difference between constant pointer and pointer
to constant.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
C Constant pointer
A pointer is said to be constant pointer when the address its pointing to cannot be changed.
L et s t ak e an ex am p l e:
char ch, c;
ptr = &c
In the above example we defined two characters (‘ch’ and ‘c’) and a character pointer ‘ptr’.
in
First, the pointer ‘ptr’ contained the address of ‘ch’ and in the next line it contained the
address of ‘c’.
n.
In other words, we can say that Initially ‘ptr’ pointed to ‘ch’ and then it pointed to ‘c’.
But in case of a constant pointer, once a pointer holds an address, it cannot change it.
This means a constant pointer, if already pointing to an address, cannot point to a new
tio
address. If we see the example above, then if ‘ptr’ would have been a constant pointer, then
the third line would have not been valid.
int main(void)
{
ch ar ch = 'c';
char c = 'a';
u
return 0;
}
When the code above is compiled, compiler gives the following error :
$ gcc -Wall constptr.c -o constptr
constptr.c: In function ‘main’:
constptr.c:9: error: assignment of read-only variable ‘ptr’
So we see that, as expected, compiler throws an error since we tried to change the address
held by constant pointer. Now, we should be clear with this concept. Lets move on.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
C Pointer to Constant
This concept is easy to understand as the name simplifies the concept. Yes, as the name
itself suggests, this type of pointer cannot change the value at the address pointed by it.
in
In the above example, we used a character pointer ‘ptr’ that points to character ‘ch’. In the
last line, we change the value at address pointer by ‘ptr’. But if this would have been a
pointer to a constant, then the last line would have been invalid because a pointer to a
n.
constant cannot change the value at the address its pointing to.
For example :
#include<stdio.h>
tio
const <type-of-pointer> *<name-of-pointer>;
int main(void)
lu
{
ch ar ch = 'c';
const char *ptr = &ch; // A constant pointer 'ptr' pointing to 'ch'
so
*ptr = 'a';// WRONG!!! Cannot change the value at address pointed by 'ptr'.
return 0;
u
}
When the above code was compiled, compiler gave the following error :
vt
So now we know the reason behind the error above ie we cannot change the value pointed to
by a constant pointer.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
C Pointer to Pointer
We have used or learned pointer to a data type like character, integer etc. But in this section
we will learn about pointers pointing to pointers. As the definition of pointer says that its a
special variable that can store the address of an other variable. Then the other variable can
very well be a pointer. This means that its perfectly legal for a pointer to be pointing to
another pointer. Lets suppose we have a pointer ‘p1′ that points to yet another pointer ‘p2′
that points to a character ‘ch’. In memory, the three variables can be visualized as : So we
can see that in memory, pointer p1 holds the address of pointer p2. Pointer p2 holds the
address of character ‘ch’. So ‘p2′ is pointer to character ‘ch’, while ‘p1′ is pointer to ‘p2′ or
in
we can also say that ‘p2′ is a pointer to pointer to character ‘ch’.
n.
ch ar * p 2 = & ch ;
But ‘p1′ is declared as :
char **p1 = &p2;
tio
So we see that ‘p1′ is a double pointer (ie pointer to a pointer to a character) and hence
the two *s in declaration.
Now,
‘p1′ is the address of ‘p2′ ie 5000
lu
‘*p1′ is the value held by ‘p2′ ie 8000
‘**p1′ is the value at 8000 ie ‘c’
so
#include<stdio.h>
int main(void)
{
char **ptr = NULL;
u
char *p = NULL;
char c = 'd';
vt
p = &c;
ptr = &p;
printf("\n c = [%c]\n",c);
printf("\n *p = [%c]\n",*p);
printf("\n **ptr = [%c]\n",**ptr);
return 0;
}
Here is the output :
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
$ ./doubleptr
c = [d ]
*p = [d]
**ptr = [d]
Introduction to Preprocessors
Preprocessor Compiler Control
You can use the cc compiler to control what values are set or defined from the command
line. This gives some flexibility in setting customised values and has some other useful
in
functions.
n.
cc -DLINELENGTH=80 prog.c -o prog has the same effect as:
#define LINELENGTH 80
Note that any #define or #undef within the program (prog.c above) override
command line
settings.
tio
You can also set a symbol without a value, for example:
cc -DDEBUG prog.c -o prog
lu
Here the value is assumed to be 1.
The setting of such flags is useful, especially for debugging. You can put commands
like:
so
#ifdef DEBUG
print("Debugging: Program Version 1\");
#else
print("Program Version 1 (Production)\");
u
#endif
Also since preprocessor command can be written an ywhere in a C program you can
vt
filter out
variables etc for printing etc. when debugging:
x = y *3;
#ifdef DEBUG
print("Debugging: Variables (x,y) = \",x,y);
#endif
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
The -E command line is worth mentioning just for academic reasons. It is not that
practical a command. The -E command will force the compiler to stop after the
preprocessing stage and output the current state of your program. Apart from being
debugging aid for preprocessor commands and also as a useful initial learning tool (try this
option out with some of the examples above) it is not that commonly used.
A data type is a classification of data, which can store a specific type of information. Data
types are primarily used in computer programming, in which variables are created to store
data. Each variable is assigned a data type that determines what type of data the variable may
in
contain.
n.
The term "data type" and "primitive data type" are often used interchangeabl y. Primitive
data types are predefined types of data, which are supported by the programming
language. For example, integer, character, and string are all primitive data types.
tio
Programmers can use these data types when creating variables in their programs. For
example, a programmer may create a variable called "lastname" and define it as a string data
type. The variable will then store data as a string of characters.
lu
Non-primitive data types are not defined by the programming language, but are instead
created by the programmer. They are sometimes called "reference variables," or "object
references," since they reference a memory location, which stores the data.
so
A stack is an ordered collection of items into which new items may be inserted and from
u
which items may be deleted at one end, called the top of the stack. A stack is a d ynamic,
constantl y changing object as the definition of the stack provides for the insertion and
vt
deletion of items. It has single end of the stack as top of the stack, where both insertion and
deletion of the elements takes place. The last element inserted into the stack is the first
element deleted-last in first out list (LIFO). After several insertions and deletions, it is
possible to have the same frame again.
Primitive Operations
When an item is added to a stack, it is pushed onto the stack. When an item is removed,
it is popped from the stack.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Given a stack s, and an item i, performing the operation push(s,i) adds an item i to the top
of stack s.
push(s, H);
push(s, I);
push(s, J);
Operation pop(s) removes the top element. That is, if i=pop(s), then the removed
element is assigned to i.
pop(s);
in
Because of the push operation which adds elements to a stack, a stack is sometimes
called a pushdown list. Conceptually, there is no upper limit on the number of items that
n.
may be kept in a stack. If a stack contains a single item and the stack is popped, the
resulting stack contains no items and is called the empty stack. Push operation is
applicable to any stack. Pop operation cannot be applied to the empty stack. If so,
tio
underflow happens. A Boolean operation empty(s), returns TRUE if stack is empty.
Otherwise FALSE, if stack is not empty.
Queues:
lu
A queue is like a line of people waiting for a bank teller. The queue has a front and a rear.
When we talk of queues we talk about two distinct ends: the front and the rear. Additions to
so
the queue take place at the rear. Deletions are made from the front. So, if a job is
submitted for execution, it joins at the rear of the job queue. The job at the front of the queue
is the next one to be executed
u
• New people must enter the queue at the rear. Push, although it is usually called an
enqueue operation.
vt
• When an item is taken from the queue, it alwa ys comes from the front. pop, although
it is usually called a dequeue operation.
What is Queue?
• Ordered collection of elements that has two ends as front and rear.
• Delete from front end
• Insert from rear end
• A queue can be implemented with an array, as shown here. For example, this queue
contains
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
Li nke d Li s ts
in
During implementation, overflow occurs. No simple solution exists for more stacks and
queues. In a sequential representation, the items of stack or queue are implicitly ordered by
the sequential order of storage.
n.
If the items of stack or queue are explicitly ordered, that is, each item contained within itself
the address of the next item. Then a new data structure known as linear linked list. Each
tio
item in the list is called a node and contains two fields, an information field and a next
address field. The information field holds the actual element on the list. The next address
field contains the address of the next node in the list. Such an address, which is used to
access a particular node, is known as a pointer. The null pointer is used to signal the end of
lu
a list. The list with no nodes – empty list or null list. The notations used in algorithms are:If
p is a pointer to a node, node(p) refers to the node pointed to by p. Info(p) refersto the
so
information of that node. next(p) refers to next address portion. If next(p) is notnull,
info(next(p)) refers to the information portion of the node that follows node(p) inthe list.
A linked list (or more clearly, "singly linked list") is a data structure that consists of a
sequence of nodes each of which contains a reference (i.e., a link) to the next node in the
u
sequence.
vt
A linked list whose nodes contain two fields: an integer value and a link to the next node.
Linked lists are among the simplest and most common data structures. They can be used to
implement several other common abstract data structures, including stacks, queues,
associative arrays, and symbolic expressions, though it is not uncommon to implement the
other data structures directly without using a list as the basis of implementation.
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
The principal benefit of a linked list over a conventional array is that the list elements can
easily be added or removed without reallocation or reorganization of the entire structure
because the data items need not be stored contiguously in memory or on disk. Linked lists
allow insertion and removal of nodes at any point in the list, and can do so with a constant
number of operations if the link previous to the link being added or removed is maintained during list
traversal.
Trees
A tree is a finite set of one or more nodes such that: (i) there is a specially designated node
in
called the root; (ii) the remaining nodes are partitioned into n 0 disjoint sets T1, ...,Tn
where each of these sets is a tree. T1, ...,Tn are called the subtrees of the root. A tree
structure means that the data is organized so that items of information are related by
n.
branches. One very common place where such a structure arises is in the investigation of
genealogies.
AbstractDataType tree{
instances
tio
A set of elements:
lu
(1) empty or having a distinguished root element
(2) each non-root element having exactly one parent element operations
so
root()
d eg re e ()
u
child(k)
}
vt
• Trees are formed from nodes and edges. Nodes are sometimes called vertices. Edges
are sometimes called branches.
• Edges are used to relate nodes to each other. In a tree, this relation is called
"parenthood."
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
• Although edges are usually drawn as simple lines, they are really directed from
parent to child. In tree drawings, this is top-to-bottom.
in
The definition is also "constructive" in that it describes how to construct a tree.
n.
2. Suppose N is a node and T1, T2, ..., Tk are trees with roots n1, n2, ...,nk, respectively. We
can construct a new tree T by making N the parent of the nodes n1, n2, ..., nk. Then, N is the
root of T and T1, T2, ..., Tk are subtrees.
tio
lu
u so
vt
More terminology
Vtusolution.in
Vtusolution.in
Programming in C and Data Structures 15PCD13
• Definition: A path is a sequence of nodes n1, n2, ..., nk such that node ni is the parent
of node ni+1 for all 1 <= i <= k.
• Definition: The length of a path is the number of edges on the path (one less than
the number of nodes).
• Definition: The descendents of a node are all the nodes that are on some path from
the node to any leaf.
in
• Definition: The ancestors of a node are all the nodes that are on the path from the
node to the root.
n.
• Definition: The depth of a node is the length of the path from root to the node. The
depth of a node is sometimes called its level.
• Definition: The height of a node is the length of the longest path from the node to a
tio
l e a f.
Vtusolution.in