Diuretic, Hypoglycemic and Limit test of Heavy metals and Arsenic.-1.pdf
Unit-I.pdf
1. UNIT 1: Introduction to Data Structures
Computer Engineering Section
University Women’s Polytechnic
Aligarh Muslim University, Aligarh
August 19, 2020
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 1 / 8
2. Outline
Basic Concepts
Data Structures: Types and Classification
Data Structure Operations
Arrays
Structures (Records)
Searching & Sorting Algorithms
- Linear Search, Binary Search & Tree Search (Unit-IV)
- Selection Sort, Bubble Sort, Merge Sort, Insertion Sort, Radix Sort &
Heap Sort (Unit-IV)
Timing Complexity: Basic Concepts
Timing complexity of searching & sorting algorithms
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 2 / 8
4. Data Structures: Formal Definition
Data may be organized in many different ways (For ex-
ample sometimes as int, float or char at other time arrays,
strings etc).
The logical or mathematical model of a particular orga-
nization is referred to as data structure.
The choice of a particular organization depends on two
considerations.
1 It must be rich enough to represent the actual relationships of data items
in real world.
2 It must be simple enough so that one can effectively process the data
whenever required.
Data structure is different from storage structure.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 4 / 8
5. Data Structure vs Storage Structure
Data structure means how different data elements are logically
related to each other.
However, storage structure means how different data elements are
physically stored in the memory of computer.
For example, in case of a 1-d array data elements are logically
continuous but physically they are contiguous.
Consider following example:
float x[50];
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 5 / 8
6. Classification of Data Structures I
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 6 / 8
7. Classification of Data Structures II
Primitive Data Structures: Primitive/ Intrinsic/ Simple data
structures are those data structures which are directly operated
upon by machine level instruction.
In other words, data structures which are directly supported by a
programming language at hand, are referred to as primitive data
structures with regard to that language.
For example with regard to C-language int, float, char, double,
pointers etc. are all primitive data structures as they can be directly
operated upon using C statements.
Non-primitive Data Structures: Also referred to as non-intrinsic/
complex/ user-defined data structures are those data structures
which are defined by the user in terms of primitive data structures.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 7 / 8
8. Classification of Data Structures III
With regard to C language arrays, structures, unions, linked list,
stacks etc. all are non-primitive as they are defined in terms of
primitive data structures.
Whether a data structure is primitive or non-primitive it strictly
depends upon the programming language at hand.
For example a 2-d array is a non-primitive data structure in C.
However for languages like Python or R, its a primitive data struc-
ture.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 8 / 8
9. Data Structure Operations I
The data appearing in data structures is processed by means of opera-
tions.
In fact, the data structure one chooses for a particular problem depend
largely on the frequency with which certain operations are performed.
In following we discuss the operations which are most commonly per-
formed on data structures:
1 Traversing or Visiting: Refers to accessing each element of a data
structure exactly once, so that certain elements could be processed.
2 Searching: Refers to finding the location of a given element (item or
key) within a data structure.
3 Inserting: Refers to adding a new element to the data structure.
4 Deleting: Refers to removing an element from the data structure.
5 Sorting: Refers to arranging the elements of a data structure in some
prescribed order (ascending or descending).
6 Merging: Refers to the process of combining the elements of two data
structures of same type and creating a new data structure of that type.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 9 / 8
10. Data Structure Operations II
Not all operations discussed above could be performed efficiently on all
data structures.
Operations which are efficient for one data structure may be inefficient
(expensive) on other data structures.
For example, with arrays search operation is efficient or at least afford-
able.
Contrary to that insertions and deletions with arrays are expensive (in-
efficient).
With linked lists search operation is as good as it is with the arrays.
However, insertions and deletions with linked lists are efficient.
Variable performance (efficiency) of operations with regard to data
structures is the main reason of the existence of so many data structures.
Note: We shall soon learn about the efficiency or performance of operations.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 10 / 8
11. Arrays: The Most Basic Data Structure I
What are arrays?
Arrays or one-dimensional arrays come into play when there is a
need to store various elements of same types under a single name.
We shall study arrays from the point of view of C-language.
Like other variables in C-language, arrays also, need to be declared
before use.
Declaring Arrays
General form of declaring an array variable say ’a’ is:
data_type a[size];
data_type indicates the type of elements (int, float, double etc.)
you want to store under the name ’a’.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 11 / 8
12. Arrays: The Most Basic Data Structure II
size indicates the maximum number of elements which could be
stored with the name ’a’.
Have a look at the following example:
float x[50];
Above statement declares 50 variables of type float.
Their names are x[0], x[1], x[2] . . . x[49].
Storage Structure for Arrays
It means ’how elements of an array are stored in the memory?’.
Again consider the following example:
float x[50];
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 12 / 8
13. Arrays: The Most Basic Data Structure III
On encountering the above declaration the compiler does the fol-
lowing:
1 Reserves 50 locations of four bytes each in memory.
2 Name these locations as x[0], x[1], x[2] . . . x[49].
3 First location is name as x[0] and the last as x[49].
4 Following figure shows the memory map:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 13 / 8
14. Arrays: The Most Basic Data Structure IV
Clearly, array elements are stored in contiguous memory locations.
By contiguous we mean adjacent (continuous) equal-sized blocks
of memory.
Accessing the Elements of an Array
Let a be a properly declared array then, ith
element of a is accessed
using the expression a[i].
Note that array index in C starts with 0. This must be kept in
mind while using the expression.
Consider the array x declared in above examples.
Then, 5th
and 20th
elements of x could be accessed using expres-
sions x[4] and x[19] respectively.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 14 / 8
15. Arrays: The Most Basic Data Structure V
Initializing Arrays
Initialization of a variable means assigning a value to the variable
at the time of declaration.
Following is an example of an initialization of an ordinary variable
p:
int p = 5;
Now the question is ’how to initialize an array when it consists of
so many elements?’
The general form of an array initialization is:
data_type array_name[size]={set of values separated by commas};
OR
data_type array_name[ ]={set of values separated by commas};
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 15 / 8
16. Arrays: The Most Basic Data Structure VI
Have a look at the initialization of array a:
int a[5] = {12, 31, 23, 5, 91};
OR
int a[ ] = {12, 31, 23, 5, 91};
Note that specifying size is optional when initializing the arrays.
When size is not specified, the compiler counts the number of
elements in the array using ’set of values’.
It then allocates memory accordingly.
If size is greater than the number of elements specified in ’set of
values’ e.g.:
int a[20] = {12, 31, 23, 5, 91};
then first five elements of array a, i.e. from a[0] to a[4] are
initialized to the values given in ’set of values’.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 16 / 8
17. Arrays: The Most Basic Data Structure VII
Rest of the array elements (i.e. from a[5] to a[19]) are initialized
to zero.
Have a look at the following examples:
Example 1: Array initialization: (size > no. of values given)
#include <stdio.h>
void main(void)
{
int a[10]={12 ,23 ,44 ,33} ,i;
for(i=0;i <10;++i) printf("%4d",a[i]);
}
Example 2:
Values 16, 91, 27, 67, 55, 72, 89, 105 are stored in an array, a. Write
a program to increase each element of the given array by 10.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 17 / 8
18. Arrays: The Most Basic Data Structure VIII
Have a look at following program:
#include <stdio.h>
void main(void)
{
int a[ ]={16 ,91 ,27 ,67 ,55 ,72 ,89 ,105} ,i;
for(i=0;i <8;++i)
{
a[i]+=10; /* Same as a[i]=a[i]+10 */
printf("%4d",a[i]);
}
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 18 / 8
19. Arrays: The Most Basic Data Structure IX
Reading (Input) Array Elements
Let a be a properly declared array of integers, then we know that
ith
element of a is accessed using the expression a[i].
The ith
element of array a could be read using the following state-
ment:
scanf("%d",&a[i]);
Using above expression, we can directly assign values to individual
elements of array a, as shown below:
a[0] = 12;
a[1] = 23;
.
.
.
a[9] = 7;
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 19 / 8
20. Arrays: The Most Basic Data Structure X
So, if we want to read (input) 10 elements in array a, we will need
to execute following set of statements:
scanf("%d",&a[0]);
scanf("%d",&a[1]);
scanf("%d",&a[2]);
.
.
.
scanf("%d",&a[9]);
Above set of statements can be replaced by the following single
statement using a loop:
for(i=0; i<10 ;++i) scanf("%d",&a[i]);
Printing (Output) Array Elements
Let a be a properly declared array of integers, then we know that
ith
element of a is accessed using the expression a[i − 1].
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 20 / 8
21. Arrays: The Most Basic Data Structure XI
The ith
element of array a could be printed using the following
statement:
printf("%d",a[i]);
So, if we want to print (output) first 10 elements of an array a,
we will need to execute following set of statements:
printf("%4d",a[0]);
printf("%4d",a[1]);
printf("%4d",a[2]);
.
.
.
printf("%4d",a[9]);
%4d specifier prints each value in a width of 4 and the values are
right justified.
In above example it is used to maintain proper gap between values
to be printed.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 21 / 8
22. Arrays: The Most Basic Data Structure XII
Above set of statements can be replaced by the following single
statement using a loop:
for(i=0; i<10 ;++i) printf("%4d",a[i]);
A Programming Example
An array consists of N elements. Write a program to increase each
element of the array by 10.
The program is listed below:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 22 / 8
23. Arrays: The Most Basic Data Structure XIII
#include <stdio.h>
int main(void)
{
int a[100] ,i,N;
printf("nEnter No. of Elements in the Array:");
scanf("%d" ,&N);
printf("nEnter %d Elements of the Arrayn",N);
/* Read elements and increase each element by 10*/
for(i=0;i<N;++i)
{
scanf("%d" ,&a[i]);
a[i]+=10;
}
/* Print elements after increment */
for(i=0;i<N;++i) printf("%4d",a[i]);
return 100;
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 23 / 8
24. Arrays: Two Dimensional (2-d) Arrays or Matrices I
What are 2-d Arrays?
2-d arrays or matrices are used when there is a need to store a
table (rows & columns) of same type of numbers under a single
name.
Like one dimensional arrays we shall study 2-d arrays from the
point of view of C-language.
Like other variables in C-language, 2-d arrays also, need to be
declared before use.
Declaring 2-d Arrays
General form of declaring a 2-d array variable say, x, is:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 24 / 8
25. Arrays: Two Dimensional (2-d) Arrays or Matrices II
data_type x[row-size] [column-size];
data_type indicates the type of table elements (int, float, double
etc.) you want to store under the name x.
row-size indicates the maximum number of rows which could be
stored with the name x.
column-size indicates the maximum number of columns which
could be stored with the name x.
Have a look at the following example:
float x[3][2];
Above statement declares a 2-d that is capable of storing six ele-
ments arranged in a table of three rows and two columns.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 25 / 8
26. Arrays: Two Dimensional (2-d) Arrays or Matrices III
Their names are x[0][0], x[0][1], x[1][0], x[1][1], x[2][1] and x[2][2].
Note that in C row & column indices start with 0.
Storage Structure for 2-d Arrays
It means ’how elements of a 2-d array are stored in the memory?’.
Again consider the following example:
float x[3] [2];
On encountering the above declaration the compiler does the fol-
lowing:
1 Reserves 6 locations of four bytes each in memory.
2 Names locations as x[0][0], x[0][1], x[1][0], x[1][1], x[2][1] and x[2][2]
3 Following figure shows the memory map:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 26 / 8
27. Arrays: Two Dimensional (2-d) Arrays or Matrices IV
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 27 / 8
28. Arrays: Two Dimensional (2-d) Arrays or Matrices V
Clearly, rows of a 2-d array are stored contiguously within the
memory.
By contiguous we mean adjacent (continuous) equal-sized blocks
of memory.
Accessing the Elements of a 2-d Array
Let a be a properly declared 2-d array then, its jth
element in ith
row is accessed using the expression a[i] [j].
Note that row and column indices in C start with 0. This must be
kept in mind while using the expression.
Initializing 2-d Arrays
The general form of a 2-d array initialization is:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 28 / 8
29. Arrays: Two Dimensional (2-d) Arrays or Matrices VI
data_type array_name[row-size][column-size]={set of values separated by commas};
OR
array_name[row-size][column-size]={{row 1 elements separated by commas}, {row 2
elements separated by commas}, {row 3 elements separated by commas}. . . };
Have a look at the initialization of array a:
int a[2][3] = {1, 1, 1, 2, 2, 2};
OR
int a[2][3] = {{1, 1, 1}, {2, 2, 2}};
When the array is completely initialized with all values, specifying
the row-size is optional.
The following initialization is perfectly acceptable:
int a[ ][3] = {1, 1, 1, 2, 2, 2};
OR
int a[ ][3] = {{1, 1, 1}, {2, 2, 2}};
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 29 / 8
30. Arrays: Two Dimensional (2-d) Arrays or Matrices VII
If the values are missing in an initializer, they are automatically set
to zero e.g.:
int a[2][3] = {{1, 1}, {2}};
assigns 1 to a[0][0] & a[0][1], and 2 to a[1][0].
Rest of the array elements are initialized to zero.
So, if we want to initialize all elements of a 2-d array to 0, it may
be done as follows:
int a[2][3] = {{0}, {0}};
Have a look at following example:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 30 / 8
31. Arrays: Two Dimensional (2-d) Arrays or Matrices VIII
/* Program demonstrates 2-d array initialization */
#include <stdio.h>
void main(void)
{
int a[2][3]={1 ,1 ,1 ,2 ,2 ,2} ,b[2][3]={{1 ,1 ,1} ,{2 ,2 ,2}} ,c
[][3]={{1 ,1 ,1} ,{2 ,2 ,2}} ,d[2][3]={{1 ,1} ,{2}} ,e
[2][3]={{0} ,{0}} ,i,j;
printf("nArray a is:");
for(i=0;i <2;++i)
{
printf("n");
for(j=0;j <3;++j) printf("%4d",a[i][j]);
}
printf("nArray b is:");
for(i=0;i <2;++i)
{
printf("n");
for(j=0;j <3;++j) printf("%4d",b[i][j]);
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 31 / 8
32. Arrays: Two Dimensional (2-d) Arrays or Matrices IX
}
printf("nArray c is:");
for(i=0;i <2;++i)
{
printf("n");
for(j=0;j <3;++j) printf("%4d",c[i][j]);
}
printf("nArray d is:");
for(i=0;i <2;++i)
{
printf("n");
for(j=0;j <3;++j) printf("%4d",d[i][j]);
}
printf("nArray e is:");
for(i=0;i <2;++i)
{
printf("n");
for(j=0;j <3;++j) printf("%4d",e[i][j]);
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 32 / 8
33. Arrays: Two Dimensional (2-d) Arrays or Matrices X
}
}
Reading (input) Elements of a 2-d Array
Let a be a properly declared 2-d array of integers, then we know
that jth
element of a in ith
row is accessed using the expression
a[i][j].
The jth
element of a in ith
row could be read using the following
statement:
scanf("%d",&a[i][j]);
Using above expression, we can directly assign values to individual
elements of a 2-d array, a, as shown below:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 33 / 8
34. Arrays: Two Dimensional (2-d) Arrays or Matrices XI
a[0][0] = 12;
a[1][0] = 23;
.
.
.
a[3][0] = 7;
If we want to read (input) elements in a 2-d array, a, consisting
of m rows and n columns (i.e. m × n array) , we need to execute
following set of statements:
for(i=0; i<m ;++i) for(j=0;j<n;++j) scanf("%d",&a[i][j]);
Printing (output) Elements of a 2-d Array
Let a be a properly declared 2-d array of integers, then we know
that jth
element of a in ith
row is accessed using the expression
a[i][j].
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 34 / 8
35. Arrays: Two Dimensional (2-d) Arrays or Matrices XII
The jth
element of a in ith
row could be printed using the following
statement:
printf("%d",a[i][j]);
Using above expression, we can directly print values of individual
elements of a 2-d array, a, as shown below:
printf("%4d",a[0][0]);
printf("%4d",a[1][0]);
.
.
.
printf("%4d",a[3][0]);
If we want to print (output) elements of a 2-d array, a, consisting
of m rows and n columns (i.e. m × n array) , in matrix form we
need to execute following set of statements:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 35 / 8
36. Arrays: Two Dimensional (2-d) Arrays or Matrices XIII
for(i=0; i<m ;++i)
{
printf("n");
for(j=0;j<n;++j) printf("%4d",a[i][j]);
}
A Programming Example
Write a program that reads two matrices a and b of order m × n
and prints their sum on standard output device.
Have a look at the following program:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 36 / 8
37. Arrays: Two Dimensional (2-d) Arrays or Matrices XIV
#include <stdio.h>
void main(void)
{
int a[10][10] ,b[10][10] ,m,n,i,j;
/* Read rows and columns in arrays */
printf("nEnter No. of Rows:"); scanf("%d" ,&m);
printf("nEnter No. of Columns:"); scanf("%d" ,&n);
/* Read arrays */
printf("nEnter Array an");
for(i=0;i<m;++i) for(j=0;j<n;++j) scanf("%d" ,&a[i][j]);
printf("nEnter Array bn");
for(i=0;i<m;++i) for(j=0;j<n;++j) scanf("%d" ,&b[i][j]);
/*Add corresponding elements of a and b and print result as
a matrix */
printf("nRESULT AFTER MATRICES ADDITIONn");
for(i=0;i<m;++i)
{
printf("n");
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 37 / 8
38. Arrays: Two Dimensional (2-d) Arrays or Matrices XV
for(j=0;j<n;++j) printf("%4d",a[i][j]+b[i][j]);
}
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 38 / 8
39. Multidimensional Arrays
We have gone through one and two dimensional arrays.
C also supports arrays with three or more dimensions. However,
they are rarely used. So we shall briefly look into them.
The general form of declaring a multidimensional array is:
data_type array_name[d1][d2][d3]...[dm];
Have a look at the following declarations of three and four dimen-
sional arrays y and z.
float y[3][5][12];
double z[2][3][4][4];
Array y is capable of holding 180 float elements while array z is
capable of holding 96 double elements.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 39 / 8
40. Data Structure Operations & Arrays I
Following table summarizes arrays from the point of view of data
structure operations:
S.No. Operation Performance (Efficiency)
1. Traversing Affordable (Efficient) & Simple
2. Searching Affordable (Moderately Efficient)
3. Sorting Affordable (Moderately Efficient)
4. Merging Affordable
5. Insertions Not Affordable (Inefficient), Complex
6. Deletions Not Affordable (Inefficient), Complex
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 40 / 8
41. Character Arrays & Strings I
What are character arrays & strings?
A Character Array is a sequence of characters that is treated as a
single data item.
A String is a sequence of characters that is treated as a single data
item. Plus, a string is terminated by a null character ’0’.
So, the difference between a character array and a string is that
the string is terminated with a special character ’0’.
Further note that any group of characters enclosed in double quotes
represents a string constant (not a character array).
C-language has no mechanism to directly read and print character
arrays. However, this feature is well supported for strings.
Indirectly character arrays can be read or printed.
Following program illustrates above concepts:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 41 / 8
42. Character Arrays & Strings II
/* array6:Program differentiates character array and
string */
#include <stdio.h>
int main(void)
{
int i;
/* Define and initialize a character array */
char p[]={ ’a’,’b’,’c’,’d’,’e’,’f’};
/* Define and initialize a String */
char s[]="abcdef";
/* Print Size of the character array and the string and
notice the difference */
printf("nSize of p=%d bytes",sizeof(p));
printf("nSize of s=%d bytes",sizeof(s));
/* Print the character array and the string and notice
printing of character array */
printf("np=%s",p);
printf("ns=%s",s);
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 42 / 8
43. Character Arrays & Strings III
/*Now print the character array as follows (indirect way
)*/
printf("np=");
for(i=0;i <6;++i) printf("%c",p[i]);
}
Clearly, strings are deal with %s specification directly.
However, character arrays are deal with %c along with some form
of looping statement.
Here, our main focus is strings as all character arrays could be
converted into strings by appending a null character to them.
Declaring Strings
The general form of declaring a string is:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 43 / 8
44. Character Arrays & Strings IV
char string_name[size];
When a character string is declared, the compiler automatically
adds a null character (’0’) to the end of string.
Therefore the size must be equal to the maximum number of char-
acters in the string plus one.
Have a look at following string declaration:
char name[30];
The string variable name is capable of holding strings of length up
to 29 characters.
Initializing Strings
The general form of initializing the string is:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 44 / 8
45. Character Arrays & Strings V
char string_name[size]={string characters enclosed in single quotes and separated by commas,’0’};
OR
char string_name[size]="string characters";
When initializing strings, specifying size is optional. So above
declarations are equivalent to:
char string_name[ ]={string characters enclosed in single quotes and separated by commas,’0’};
OR
char string_name[ ]="string characters";
So, all the following declarations are identical:
char institute[12]={’P’,’o’,’l’,’y’,’t’,’e’,’c’,’h’,’n’,’i’,’c’,’0’};
char institute[12]="Polytechnic";
char institute[ ]={’P’,’o’,’l’,’y’,’t’,’e’,’c’,’h’,’n’,’i’,’c’,’0’};
char institute[ ]="Polytechnic";
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 45 / 8
46. Character Arrays & Strings VI
When initializing, if size specified is larger than the number of
characters supplied, the additional characters of the string are filled
with ’0’ character.
Consider the following declaration:
char Name[10]="JOHN";
Following figure shows the memory layout for string variable Name.
Reading Strings
1. Using scanf function:
scanf function with %s format specifier can be used to read a
properly declare string as shown below:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 46 / 8
47. Character Arrays & Strings VII
char name[20];
scanf("%s",name);
The problem with scanf is that it terminates its input as soon as
it encounters a white space.
A white space includes blanks, tabs, carriage returns, new lines
and form feeds.
So, in above example if we input "John Deer" to be assigned to
name, only "John" is stored in it.
However, the scanned portion of string is terminated with a ’0’,
the additional places in string are filled with garbage(?).
So, memory layout for string name looks as follows:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 47 / 8
48. Character Arrays & Strings VIII
Clearly, if we want to read the name "John Deer", with
scanf we need to declare two strings.
Following program illustrates:
/* array7: Reading strings using scanf */
#include <stdio.h>
void main(void)
{
char name [20],s1[10],s2 [10];
int i;
printf("nEnter Name as John Deer:");
scanf("%s",name);
printf("nScanned in name =%s",name);
printf("n");
/* Verify that garbage values are stored in assigned
locations */
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 48 / 8
49. Character Arrays & Strings IX
for(i=5;i <20;++i) printf("%c",name[i]);
/* Scan the name John Deer again in two strings s1 and s2
*/
printf("nEnter name John Deer again:");
fflush(stdin);
scanf("%s%s",s1 ,s2);
printf("nScanned name this time =%s %s",s1 ,s2);
}
There is still a way in C to read a string with white spaces using
scanf.
C supports a format specification known as the edit set conversion
code (%[ ∧
... ]).
This specification can be used to read a line containing a variety
of characters, including white spaces..
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 49 / 8
50. Character Arrays & Strings X
Have a look at following program which reads a string until a
newline character is encountered.
/* array8: Demonstrates reading of strings with white spaces
using scanf */
#include <stdio.h>
void main ()
{
char str [1000 ];
printf("Enter a string");
/* scan whole string , including the white spaces till n
is encountered */
scanf("%[^n]", str);
printf("%s", str);
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 50 / 8
51. Character Arrays & Strings XI
2. Using gets function:
Another conventional method of reading a string with white spaces
is utilizing the gets function from stdio.h.
Let str be a properly declared string then the statement:
char str[40];
gets(str);
reads characters into str from the keyboard until a new line char-
acter is encountered.
It also appends a null character(’0’) to str.
Have a look at following program:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 51 / 8
52. Character Arrays & Strings XII
/* array8: Demonstrates gets function */
#include <stdio.h>
void main ()
{
char str [40];
printf("Enter a string:");
/* read whole string , including the white spaces till n
is encountered */
gets(str);
printf("%s", str);
}
3. Using getchar function:
In principle getchar function is used to read a single character from
the keyboard.
We can use this function repeatedly to read a string.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 52 / 8
53. Character Arrays & Strings XIII
Have a look at following program which demonstrates same con-
cept.
/* array10: Demonstrates reding string using getchar ()*/
#include <stdio.h>
void main(void)
{
char c, str [100];
int i=0;
while (1)
{
c=getchar ();
if(c==’n’) break;
str[i++]=c;
}
str[i]=’0’;
printf("nString Read Is:%s",str);
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 53 / 8
54. Character Arrays & Strings XIV
The same program may be reproduced in following compact form:
/* array11: Demonstrates reding string using getchar ():
compact form */
#include <stdio.h>
void main(void)
{
char c, str [100];
int i=0;
while ((c=getchar ())!=’n’) str[i++]=c;
str[i]=’0’;
printf("nString Read Is:%s",str);
}
Another Example:
Write a program to read and print a paragraph of text.
Following program demonstrates:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 54 / 8
55. Character Arrays & Strings XV
/* array12: Demonstrates reading and printing a paragraph of
text */
#include <stdio.h>
void main(void)
{
char c, str [1000];
int i=0;
while ((c=getchar ())!=EOF) str[i++]=c;
str[i]=’0’;
printf("nString Read Is:%s",str);
}
The above program works well but we are still bound to follow the
limit of the array declared to store the characters read.
How to get rid of this? The following program demonstrates:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 55 / 8
56. Character Arrays & Strings XVI
/* array13: Demonstrates reading and printing a paragraph of
text */
#include <stdio.h>
void main(void)
{
char c;
while ((c=getchar ())!=EOF) putchar(c);
}
Printing Strings
1. Using printf function:
Let str be a string declared properly and terminated with a ’0’,
then it can be printed using printf as follows:
printf("%s",str);
We can also specify the precision with which the string is printed.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 56 / 8
57. Character Arrays & Strings XVII
%w.ks: specifies that first k characters of the string are to be
printed in a field width of w columns and the printed string is
right-justified.
If we include a minus sign with the specification (-%w.ks), the
string is printed left-justified.
It is important to note that when field width is less than the length
of the string, the entire string is printed.
Following program illustrates:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 57 / 8
58. Character Arrays & Strings XVIII
/* array14: Demonstrates string formatting while printing */
#include <stdio.h>
void main(void)
{
char institute []="University Women ’s Polytechnic";
printf("n%10s",institute);
printf("n%40s",institute);
printf("n%-40s",institute);
printf("n%20.10s",institute);
printf("n% -20.10s",institute);
}
The gcc compiler supports another nice feature that allows for
variable field width or precision. For instance the statement:
printf("%*.*sn",w,k,str);
prints the first k characters of the string str in a field width of w.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 58 / 8
59. Character Arrays & Strings XIX
Following program illustrates:
/* array15: Demonstrates string variable formatting while
printing */
#include <stdio.h>
void main(void)
{
char institute []="Polytechnic";
int i,k;
for(i=0;i <11;++i){
k=i+1;
printf("% -11.*sn",k,institute);
}
for(i=10;i>=0;--i){
k=i+1;
printf("% -11.*sn",k,institute);
}
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 59 / 8
60. Character Arrays & Strings XX
2. Using puts function:
Another convenient way of printing a string is using puts function
from stdio.h.
However, this function doesn’t support any formatting.
Let str be a string declared properly and terminated with a ’0’,
then it can be printed using puts function as follows:
puts(str);
3. Using putchar function:
A string can also be printed using printf("%c",ch) or putchar func-
tion.
Both are the ways of printing a string on character by character
basis.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 60 / 8
61. Character Arrays & Strings XXI
Following program illustrates:
/* array16: Demonstrates putchar function */
#include <stdio.h>
void main(void)
{
char institute []="University Women ’s Polytechnic";
int i=0;
while(institute[i]!=’0’)
{
putchar(institute[i]);
/* same as printf (%c,institute[i]*/
i++;
}
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 61 / 8
62. Character Arrays & Strings XXII
Operations on String
One string can’t be assigned to another. If str1 and str2 be two
properly declared strings then the statement:
str1 = str2
is not admissible in C.
Two strings can’t be added. If str1 and str2 be two properly
declared strings then the statement:
str1 + str2
is not admissible in C.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 62 / 8
63. Character Arrays & Strings XXIII
Two strings can’t be compared. If str1 and str2 be two properly
declared strings then the statement:
if (str1 == str2) . . .
is not admissible in C.
Fortunately, the C-library supports a large number of string han-
dling functions that can be used to carry out many of the string
manipulations.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 63 / 8
64. Character Arrays & Strings XXIV
String Handling Functions
Following table summarizes important string handling functions:
S.No. Function Description
1. strcat(str1, str2) Joins two strings. str2 is appended (joined at the
end) to str1. Clearly, str1 should be large enough to
hold both str1 and str2.
2. strlen(str) Finds the length of str (excluding null character).
3. strcpy(str1, str2) Assigns contents of str2 to str1. Clearly, str1 should
be large enough to hold str2. str2 remains unaltered
after the operation.
4. strcmp(str1, str2) Compares str1 and str2. Returns 0, if strings are
identical otherwise the numeric difference between the
ascii vales of first non-matching characters is returned.
5. strcmpi(str1, str2) Same as strcmp() but, strcmpi() function is not
case sensitive i.e, "A" and "a" are treated as same
characters.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 64 / 8
65. Character Arrays & Strings XXV
6. strncpy(str1, str2, n) Copies first n characters of str2 to str1. Yet again str1
should be large enough to sustain with the operation.
Since first n characters of str2 may not have ’0’, we
have to explicitly assign it to str1 to make it a proper
string.
7. strncmp(str1, str2, n) Instead of whole string, first n characters of str2 are
compared with str1 and rest of the functionality is
identical to strcmp().
8. strncat(str1, str2, n) Instead of whole string, first n characters of str2 are
appended to str1. Since first n characters of str2 may
not have ’0’, we have to explicitly assign it to str1
to make it a proper string. Moreover str1 should be
large enough to sustain with the operation.
9. strstr(str1, str2) Searches the string str1 to check whether str2 is con-
tained in str1. If yes it returns the position of the
first occurrence of str2 in str1. Otherwise, it returns
a NULL pointer.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 65 / 8
66. Character Arrays & Strings XXVI
Note: Don’t forget to include the header file string.h when
using above functions.
Following program illustrates several of these functions:
/* array17: Demonstrates string handling functions */
#include <stdio.h>
#include <string.h>
void main(void)
{
char s[40],p[15];
printf("nEnter s:");gets(s);
fflush(stdin);
printf("nEnter p:");gets(p);
printf("nLength of %s is %d and that of %s is %d",s,
strlen(s),p,strlen(p));
strcat(s,p);
printf("nStrings After Joining =%s",s);
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 66 / 8
67. Character Arrays & Strings XXVII
strcpy(s,p);
printf("nStrings After Copy Operation =%s",s);
if(strcmp(s,p)==0) printf("nStrings now are equal");
else printf("nStrings are not equal");
strncat(s,p,4);
printf("nString After Operation =%s",s);
printf("nResult of=%s",strstr(s,"am"));
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 67 / 8
68. Character Arrays & Strings XXVIII
Arrays of Strings (2-d Character Arrays)
Sometimes there is a need to store a table of strings like the one
shown in following figure:
A two dimensional character array (aray of strings) can be utilized
to store such a table as shown below:
char names[ ][size]=
{
"Smith",
"Blake",
"John Deer",
"..."
"Ada Simon"
};
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 68 / 8
69. Character Arrays & Strings XXIX
Note that size, which indicates the maximum length of a string
the 2-d character array can store, is mandatory to specify.
The ith
name in the above 2-d character array could be accessed
using the expression names[i] (remembering that array index in C
starts with 0).
Following program illustrates the concept:
/* array18: Demonstrates 2-d strings. Finds length of each
string in table */
#include <stdio.h>
#include <string.h>
void main(void)
{
char s[][30]={"Virat Kohli","Shikhar Dhawan","KL Rahul",
"Mahendra Singh Dhoni","Mohammad Sami","Jasprit Bumrah"
};
int i;
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 69 / 8
70. Character Arrays & Strings XXX
for(i=0;i <6;++i) printf("nLength of %s=%d",s[i],strlen(
s[i]));
}
If you wish you can use a variable 2-d character array as following
program illustrates:
/* array19: Demonstrates 2-d strings. Finds length of
variable 2-d strings
*/
#include <stdio.h>
#include <string.h>
void main(void)
{
char s[5][30];
int i;
printf("nEnter five strings :n");
for(i=0;i <5;++i)
{
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 70 / 8
71. Character Arrays & Strings XXXI
gets(s[i]);
fflush(stdin);
}
for(i=0;i <5;++i) printf("nLength of %s=%d",s[i],strlen(
s[i]));
}
2-d character arrays become more interesting and efficient when
accessed using pointers.
We shall look into that shortly.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 71 / 8
72. Structures and Unions I
What are Structures?
Structures or Unions come into play when there is a need to store
several data items of different types under a single name.
Clearly, a structure or a union is a method of packing heteroge-
neous data items into a single entity.
The data items which are packed into a single entity are referred
to as members of structure
Structures and Unions are almost similar yet some differences do
exist between them.
Unions are utilized in some special situations which we shall learn
in the end of chapter.
Like other variables in C-language, structures also need declaration
before they could be used.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 72 / 8
73. Structures and Unions II
Declaring Structures
Structures are declared using the keyword struct.
Declaration of structures slightly differs from the declaration of
other normal variables or arrays.
While declaring a structure, first we declare the base skeleton or
format or template of the structure.
Then, variables of structure types are declared subsequently.
There are several ways of declaring them. We examine each of
them briefly:
1 1. Using a tag_name
General form of this declaration is:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 73 / 8
74. Structures and Unions III
struct tag_name
{
data_type 1 member1;
data_type 2 member2;
.
.
.
data_type n membern;
};
Now, the general form of declaring variables of the type of structure
tag_name is:
struct tag_name var_1, var_2 . . . var_n;
Following is an example:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 74 / 8
75. Structures and Unions IV
struct address
{
char name[40];
int hno;
char street[70];
char pincode[7];
};
Now, variables of the type of structure address could be created
using following statement:
struct address ad1, ad2, ad3 . . . adn;
2 Without a tag_name
The general form of this kind of declaration is:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 75 / 8
76. Structures and Unions V
struct
{
data_type 1 member1;
data_type 2 member2;
.
.
.
data_type n membern;
} ad1, ad2, ad3 . . . adn;
The list of variables of type structure appears immediately after
structure definition.
Following this form the structure and variables declared in above
example could be declared as below:
struct
{
char name[40];
int hno;
char street[70];
char pincode[7];
} ad1, ad2 . . . adn;
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 76 / 8
77. Structures and Unions VI
This approach looks convenient but is not recommended because
without a tag_name it is not possible to refer the structure in
future.
3 Using typedef Staement
Structures defined using this approach are referred to as ’Type
Defined Structures’. The general from of this declaration is:
typedef struct
{
data_type 1 member1;
data_type 2 member2;
.
.
.
data_type n membern;
} record;
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 77 / 8
78. Structures and Unions VII
Now, variables of the type of structure could be declared using the
keyword record as follows:
record var_1, var_2 . . . var_n;
Following this form the structure and variables declared in above
examples could be declared as below:
typedef struct
{
char name[40];
int hno;
char street[70];
char pincode[7];
} address;
Now variables of type structure can be declared using the keyword
address as follows:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 78 / 8
79. Structures and Unions VIII
address ad1, ad2, ad3 . . . adn;
Most of the time we shall follow this method of structures decla-
ration.
An Example: Following program illustrates all the three meth-
ods of structures declaration:
/* array20: Demonstrates structures declarations: Three ways
*/
#include <stdio.h>
void main(void)
{
/* First Method: Using tag_name */
struct address
{
char name [40];
int hno;
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 79 / 8
80. Structures and Unions IX
char street [70];
char pincode [7];
};
struct address ad11 ,ad12 ,ad13;
/* Secong Method: Without tag_name */
struct
{
char name [40];
int hno;
char street [70];
char pincode [7];
} ad21 ,ad22 ,ad23;
/* Third Method: Using typedef */
typedef struct
{
char name [40];
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 80 / 8
81. Structures and Unions X
int hno;
char street [70];
char pincode [7];
} addrecord;
addrecord ad31 ,ad32 ,ad33;
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 81 / 8
82. Structures and Unions XI
Memory Layout for Structures
Consider the following structure declaration:
typedef struct
{
char street[70];
int hno;
char name[40];
char pincode[7];
} address;
address a1,a2,a3;
On encountering the structure definition (typedef struct{....}) the
compiler knows that each variable of this structure would require
119 bytes in the memory.
We have declare three variables (a1, a2 & a3) of type structure.
So the compiler reserves 357 bytes in the memory comprising of
three blocks of 119 bytes each.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 82 / 8
83. Structures and Unions XII
The first block is assigned to a1, the second to a2 and the third
to a3.
Clearly structure variables are stored in contiguous memory loca-
tions.
Following figure shows a memory layout for the structure variables.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 83 / 8
84. Structures and Unions XIII
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 84 / 8
85. Structures and Unions XIV
Accessing Structure Members
Let x be a properly declared structure variable with members
m1, m2, ,̇mn then accessing a member of x follows below listed
general form:
variable_name.member_name;
So, members of x could be accessed as follows:
x.m1;
x.m2;
x.m3;
.
.
.
x.mn;
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 85 / 8
86. Structures and Unions XV
Clearly, members of the variable a1 of structure type address de-
clared in above examples, could be accessed as follows:
a1.street;
a1.hno;
a1.name;
a1.pincode;
Similarly, members of structure variables a2 and a3 could be ac-
cessed.
Initializing Structure Variables
As already pointed out that initialization means assigning values
at the time of declaration.
We have three methods of declaring structures. Consequently
there are three ways of initializing structure variables.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 86 / 8
87. Structures and Unions XVI
1 Method 1: Corresponds to declaration with a tag_name:
Have a look at the following example:
struct address
{
char name[40];
int hno;
char street[70];
char pincode[7];
};
Now, variables of the type of structure address could be initialized as
follows:
struct address ad1={"Smith",20,"Wall Street","201200"}, ad2={"Jones",22,"Hill
Street","201201"};
2 Method 2: Corresponds to declaration without a tag_name:
Have a look at the following example:
struct
{
char name[40];
int hno;
char street[70];
char pincode[7];
} ad1={"Smith",20,"Wall Street","201200"}, ad2={"Jones",22,"Hill Street","201201"};
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 87 / 8
88. Structures and Unions XVII
3 Method 3: Corresponds to typedef declaration
Have a look at the following example:
typedef struct
{
char name[40];
int hno;
char street[70];
char pincode[7];
} address;
Now variables of type structure can be initialized using the keyword
address as follows:
address ad1={"Smith",20,"Wall Street","201200"}, ad2={"Jones",22,"Hill
Street","201201"};
Have a look at following program:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 88 / 8
89. Structures and Unions XVIII
/* array21: Demonstrates initialization of structure
variables */
#include <stdio.h>
void main(void)
{
/* First Method: Using tag_name */
struct address
{
char name [40];
int hno;
char street [70];
char pincode [7];
};
struct address ad11 ={"Smith" ,20,"Wall Street","201200"},
ad12 ={"Jones" ,22,"Hill Street","201201"};
/* Secong Method: Without tag_name */
struct
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 89 / 8
90. Structures and Unions XIX
{
char name [40];
int hno;
char street [70];
char pincode [7];
} ad21 ={"Smith" ,20,"Wall Street","201200"},ad22 ={"Jones"
,22,"Hill Street","201201"};
/* Third Method: Using typedef */
typedef struct
{
char name [40];
int hno;
char street [70];
char pincode [7];
} addrecord;
addrecord ad31 ={"Smith" ,20,"Wall Street","201200"},ad32
={"Jones" ,22,"Hill Street","201201"};
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 90 / 8
91. Structures and Unions XX
}
Rules applicable to structure initialization:
- Individual members can’t be initialized inside structure template.
- The order of the values enclosed in braces should match the order of
members in the structure definition.
- Partial initialization is allowed i.e. some members of structure variable(s)
could be left blank.
- The rule here is that the uninitialized members should be only at the
end of the list of members.
- The uninitialized numeric (integer or real) members default to 0 while
uninitialized strings or characters default to ’0’.
Giving Values to Structure Variables
Two ways are there:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 91 / 8
92. Structures and Unions XXI
1. Direct Assignment:
Let x be a properly declared structure variable with members
m1, m2, ,̇mn, then we know that the nth
member of x could be
accessed using the expression x.mn.
Using same concept value to the nth
member of x could be passed
as follows:
x.mn = value; (if mn is of numeric type)
OR
x.mn =0 value0; (if mn is represents a single character)
OR
strcpy(x.mn, ”value”); (if mn is a character string)
2. Reading from Terminal:
Let x be a properly declared structure variable with members
m1, m2, ,̇mn, then we know that the nth
member of x could be
accessed using the expression x.mn.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 92 / 8
93. Structures and Unions XXII
Using same concept value to the nth
member of x could be passed
from terminal as follows:
scanf (”%d or %f or . . . ”, &x.mn); (if mn is of numeric type)
OR
scanf (”%c”, &x.mn); (if mn is represents a single character)
OR
scanf (”%s”, x.mn); (if mn is a character string)
Output/ Printing Structure Variables
Let x be a properly declared structure variable with members
m1, m2, ,̇mn, then we know that the nth
member of x could be
accessed using the expression x.mn.
Using same concept value of the nth
member of x could printed as
follows:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 93 / 8
94. Structures and Unions XXIII
printf (”%d or %f or . . . ”, x.mn); (if mn is of numeric type)
OR
printf (”%c”, x.mn); (if mn is represents a single character)
OR
printf (”%s”, x.mn); (if mn is a character string)
Have a look at following program:
/* array22: Demonstrates giving/printing values to/of
structure variables */
#include <stdio.h>
#include <string.h>
void main(void)
{
typedef struct
{
char name [40];
int hno;
char street [70];
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 94 / 8
95. Structures and Unions XXIV
char pincode [7];
} addrecord;
addrecord ad1 , ad2 ,ad3;
/* Direct Assignment of values to ad1*/
strcpy(ad1.name ,"Smith");
ad1.hno =20;
strcpy(ad1.street ,"Wall Street");
strcpy(ad1.pincode ,"201200");
/* Copying array variables */
ad3=ad1;
/* Reading values from terminal for ad2*/
printf("nEnter data for ad2n");
gets(ad2.name);
fflush(stdin);
scanf("%d" ,&ad2.hno);
fflush(stdin);
gets(ad2.street);
fflush(stdin);
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 95 / 8
96. Structures and Unions XXV
gets(ad2.pincode);
printf("nDetails of %sn",ad1.name);
printf("nHouse No.=%d",ad1.hno);
printf("nStreet =%s",ad1.street);
printf("nPincode =%s",ad1.pincode);
printf("n------------------------------------");
printf("nDetails of %sn",ad2.name);
printf("nHouse No.=%d",ad2.hno);
printf("nStreet =%s",ad2.street);
printf("nPincode =%s",ad2.pincode);
printf("nDetails of %sn",ad3.name);
printf("nHouse No.=%d",ad3.hno);
printf("nStreet =%s",ad3.street);
printf("nPincode =%s",ad3.pincode);
printf("n------------------------------------");
printf("nSize of Long Integer =%d",sizeof(long));
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 96 / 8
97. Structures and Unions XXVI
Arrays of Structures
We have arrays of integers, floats, doubles and characters etc.
Can we have arrays of structures??
Yes, have a look at the following example which declares an array
of complex numbers:
typedef struct
{
float rp,cp;
} cnumber;
cnumber cn[100];
In above example we declare an array of 100 complex numbers
(cn[0], cn[1], cn[2] . . . cn[99]).
Each variable cn[k], 0 ≤ k ≤ 99, is of the type of cnumber struc-
ture.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 97 / 8
98. Structures and Unions XXVII
The members of any cn[i], 0 ≤ i ≤ 99, could be referred to as
cn[i].rp & cn[i].cp.
Following figure shows memory allocation for array cn[i], 0 ≤ i ≤
99:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 98 / 8
99. Structures and Unions XXVIII
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 99 / 8
100. Structures and Unions XXIX
Qn: WAP to add n complex numbers.
Copying & Comparing structure variables
Two variables of same structure types can be copied the same way
as ordinary variables.
However, two variables of same structure types can’t be compared.
if x and y are two variables of same structure type then:
- x = y; is valid.
- x == y or x! = y etc. are invalid.
Furthermore, two structure variables can be compared on member-
to-member basis.
Structures within structures
Have a look at following declaration:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 100 / 8
101. Structures and Unions XXX
typedef struct
{
char eno[10], name[40];
float fee;
struct
{
int dd,mm,yy;
} dob;
} record;
record x;
The elements of internal structure could be accessed as follows:
x.dob.dd;
x.dob.mm;
x.dob.yy;
Qn: WAP to demonstrate the concept of structures withing
structures.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 101 / 8
102. Structures and Unions XXXI
Unions
Unions are a concept borrowed from structures and therefore they
follow the same syntax as structures.
However, there is a major difference between the structures and
unions in terms of storage.
In structures, each member has its own storage location, whereas
all the members of a union share the same storage location.
It implies that although a union can have many members of dif-
ferent types, it can handle only one member at a time.
Union is declared in the same way as the structure.
When we intend to declare a union the struct keyword is replaced
by the keyword union.
Have a look on following example:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 102 / 8
103. Structures and Unions XXXII
typedef union
{
int x;
float y;
char c;
} record;
record u;
The above definition declares a variable u of record union type.
The union contains three members each with different data types.
However, we can use only one of them at a time.
This is due to the fact that only one location is allocated for a
union variable, irrespective of its size.
The compiler allocates a block of storage which is large enough to
hold the biggest member of the union variable.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 103 / 8
104. Structures and Unions XXXIII
In above declaration the member y, which requires 4 bytes is the
largest among the members.
So, the compiler allocates 4 bytes to store all members of the
union.
Following figure shows how all the three members share the same
memory block.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 104 / 8
105. Structures and Unions XXXIV
To access union members, we use the same syntax as with struc-
tures. Following is an example:
u.x;
u.y;
u.c;
While accessing however, we should make sure that we are access-
ing the member whose value is currently stored. For example:
u.x=115;
u.y=333.97;
printf("nx=%d",u.x);
will produce error (why??).
The correct code must be:
u.x=115;
printf("nx=%d",u.x);
u.y=333.97;
printf("ny=%f",u.y);
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 105 / 8
106. Structures and Unions XXXV
Have a look at following program:
/* array23: Demonstrates size of structure and union plus how
to access union members */
#include <stdio.h>
void main(void)
{
typedef struct
{
int x;
float y;
char c;
} srecord;
typedef union
{
int x;
float y;
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 106 / 8
107. Structures and Unions XXXVI
char c;
} urecord;
urecord u;
printf("nSize of structure =%d",sizeof(srecord));
printf("nSize of union =%d",sizeof(urecord));
u.x=155;
printf("nu.x=%d",u.x);
u.y=333.97;
printf("nu.y=%f",u.y);
}
Size of a structure
Is size of a structure is equal to the sum of the size of all of its
member?
The answer is compiler dependent.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 107 / 8
108. Structures and Unions XXXVII
The sizeof for a struct is not always equal to the sum of sizeof of
each individual member.
This is because of the padding (slack bytes) added by the compiler
to avoid alignment issues.
Padding is only added when a structure member is followed by a
member with a larger size or at the end of the structure.
Different compilers might have different alignment constraints.
Have a look at following program:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 108 / 8
109. Structures and Unions XXXVIII
/* array24: Demonstrates slack bytes */
#include <stdio.h>
void main(void)
{
typedef struct
{
char ch;
int i;
} st_demo;
st_demo s;
printf(" Size of int = %d nn Size of char = %d nn
Size of struct = %d ",sizeof(s.i), sizeof(s.ch),sizeof(s
));
}
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 109 / 8
110. Searching & Sorting on Arrays I
Searching
Linear Search
Binary Search
Under Development
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 110 / 8
111. Complexity of Algorithms I
Complexity of an Algorithm
Any good algorithm should satisfy following two obvious condi-
tions:
1 Should compute correct (desired) output (for the given problem).
2 Should be effective ("fast").
Complexity of algorithm measures how "fast" is the algorithm
(time complexity) and what "amount" of memory it uses (space
complexity).
Time and memory are two basic resources in computations.
Our goal here is to focus on the timing complexity of the algorithm.
As far as space complexity is concerned, it is always easy to com-
pute looking at the variables used when the algorithm is coded
into a program.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 111 / 8
112. Complexity of Algorithms II
The basic question is "How to measure how fast (or slow) an
algorithm is?"
There are two issues to be considered when designing such a mea-
sure:
1 Independence on any programming language (and hardware/software
platform).
2 Maximum independence on particular input data. It should be an
internal property of the algorithm itself.
An idea: Count basic operations of the algorithm and one shall be
able to guess the timing complexity.
Simplification: it is not necessary to count all the operations - it
would be enough to count the "representative" ones.
Before attempting to a complexity analysis two steps must be done:
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 112 / 8
113. Complexity of Algorithms III
1 Determine the dominating operation set.
2 Observe what (in input) influences the number of dominating
operations (data size)
Dominating operations are those which cover the amount of work
which is proportional to the whole amount of work of the algorithm
(they well represent the whole).
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 113 / 8
114. Complexity of Algorithms IV
What can be the dominating operation set in the following algo-
rithm?
Algorithm
1: find(arr, len, key) {
2: i = 0
3: while (i < len) do
4: if (arr[i] == key) then
5: return i
6: end if
7: i + +
8: end while
9: return −1 }
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 114 / 8
115. Complexity of Algorithms V
Dominating Operations?
- Assignment i = 0? No
- Comparison i < len? Yes
- Comparison arr[i] == key? Yes
- return statement return i? No
- increment i + +? Yes
What is the data (input) size in the above algorithm?
Data (Input) size: length of the array arr.
Having determined the dominating operation and data size we can
determine time complexity of the algorithm.
Time Complexity of an algorithm is the number of dominating
operations executed by the algorithm as the function of data size.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 115 / 8
116. Complexity of Algorithms VI
Time complexity actually measures the "amount of work" done
by the algorithm during solving the problem in the way which is
independent on the implementation and particular input data.
The lower the time complexity is, the "faster" is the algorithm.
For above algorithm:
Dominating operation: comparison (arr[i] == key)
Data size: the length of array (denote by n)
Thus, the number of dominating operations executed by this algo-
rithm ranges:
from 1 (the key was found under the first index) : We call it Best Case.
to n (the key is absent or under the last index) : Accordingly, this is
called worst case.
Best case is the function which performs the minimum number of
steps on input data of n elements.
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 116 / 8
117. Complexity of Algorithms VII
Worst case is the function which performs the maximum number
of steps on input data of size n.
Average case is the function which performs an average number
of steps on input data of n elements.
Following table shows timing complexities of various searching and
sorting algorithm:
Searching Algorithms
SNo. Algorithm Best Case Worst Case Average Case
1. Linear Search O(1) O(n) O(n)
2. Binary Search O(1) O(log2 n) O(log2 n)
Sorting Algorithms
1. Selection Sort O(n2
) O(n2
) O(n2
)
2. Bubble Sort O(n) O(n2
) O(n2
)
3. Merge Sort O(n log2 n) O(n log2 n) O(n log2 n)
4. Insertion Sort O(n) O(n2
) O(n2
)
5. Radix Sort - O(n2
) O(n log2 n)
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 117 / 8
118. Complexity of Algorithms VIII
Note: On Timing Complexity of Radix Sort:
Let the maximum number of digits in any item of array A (the
array to be sorted using radix sort) be s.
The array A, has n items and r is the radix on which each item
of A is represented (10 for decimal, 2 for binary etc.) then the
complexity of radix sort is bounded by the following inequality:
C(n) ≤ r ∗ s ∗ n
Dr. J. Alam (CES) Unit 1: Introduction August 19, 2020 118 / 8