2. Points to be covered
– Concept of Array
– Strings
– Structures
– Algorithms
– Complexity
3. Introduction to Array
• Array is a data structure that represents a collection of the same types of
data by a common name.
• Compared to the basic data type (int, float & char) it is an aggregate or
derived data type.
• All the elements of an array occupy a set of contiguous memory locations.
• Why need to use array type?
Consider the following issue:
"We have a list of 1000 students' marks of an integer type. If using the
basic data type (int), we will declare something like the following…"
int studMark0, studMark1, studMark2, ...,
studMark999;
4. Arrays
• By using an array, we just declare like this,
• int studMark[1000];
• This will reserve 1000 contiguous memory locations for storing the
students’ marks.
5. Declaring Array
• When declaring arrays, specify
– Type of array
– Name
– Number of elements
arrayType arrayName[ numberOfElements];
– Examples:
int c[10];
float myArray[3000];
• Declaring multiple arrays of same type
int b[100],x[27];
6. Declaring Array
For example, to declare an array of 30 characters, that construct a
people name, we could
declare,
char cName[30];
Which can be depicted as follows,
In this statement, the array character can
store up to 30 characters with the first
character occupying location cName[0] and
the last character occupying cName[29].
- Note that the index runs from 0 to 29. In C, an index always starts
from 0 and ends with array's (size-1).
7. Initialization
• An array may be initialized at the time of declaration.
• Initialization of an array may take the following form,
type array_name[size] = {a_list_of_value};
For example:
• int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
• float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
• char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '0'};
• Note the last character in chVowel is NULL character ('0')
9. Assessing elements
• An element is accessed by indexing the array name.
• This is done by placing the index of the element within square brackets
after the name of the array.
Example:-
int main()
{
int i;
int a[5]={1,2,3,4,5};
for(i=0;i<5;i++)
{
printf(“%dt”, a[i])
}
}
10. Storage Representation
• 1-d array are linear array in which elements are stored in the
successive memory locations.
• The element at the very first position in the array is called its
base address.
• Suppose name of linear array is arr of type int and it has 5
elements with base address start from 1024. Then it is
represented as:
offset :- 0 4 8 12 16
index :- 0 1 2 3 4
value:-
Address:- 1024 1028 1032 1036 1040
14 46 4 86 23
11. Multidimensional array
• C programming language allows multidimensional arrays.
• The general form of a multidimensional array declaration −
type name [size1][size2]… .[sizeN];
• For example, the following declaration creates a two
dimensional integer array
int twoDimension[5][4];
12. Two-dimensional Arrays
• The simplest form of multidimensional array is the two-dimensional array.
• A two-dimensional array is, in essence, a list of one-dimensional arrays.
• Syntax:
type arrayName [x][y];
• A two-dimensional array a[3][4], which contains three rows and four
columns can be shown as follows-
13. Initializing Two-Dimensional Arrays
• Multidimensional arrays may be initialized by specifying
bracketed values for each row.
• Following is an array with 3 rows and each row has 4
columns.
• The nested braces, which indicate the intended row, are
optional. The following initialization is equivalent to the above
example −
14. Accessing Two-dimensional array
• An element in a two-dimensional array is accessed by using
the subscripts, i.e., row index and column index of the array.
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %dn", i,j, a[i][j] );
}
}
return 0;
}
0 0
1 2
2 4
3 6
4 8
15. Introduction to String
• Strings are array of characters i.e. they are characters arranged
one after another in memory. Thus, a character array is called
string.
• Each character in a string occupies one location in an array.
• A string is always terminated by a null character (i.e. slash
zero 0).
VIIT, Pune 15
16. Declaration
• A string variable is declared as an array of characters.
Syntax:
char string_name[size];
e.g. char s[5];
• When the compiler assigns a character string to a
character array, it automatically supplies a null character
(‘0’) at the end of the string
VIIT, Pune 16
17. Initialization
Initialization Syntax:
char myString [] = { 'H','A','E','S', 'L', 'E', 'R', '0' } ;
char myString[13] = “Initial value”
char myString[] = “Initial value”;
0 = null character
Note: that ‘0’ and ‘0’ are not same.
• When we initialize a character array by listing its elements, the null
terminator or the size of the array must be provided explicitly.
• When declaring a string don’t forget to leave a space for the null
character which is also known as the string terminator character
because it is only way the functions that work with a string can know
where the string ends.
n i t i a l v a l u e ? ? …
I 0
Compilation time
initialization
VIIT, Pune 17
19. • Memory for strings must be allocated before the string can be
used.
• A string literal is enclosed in double quotes
VIIT, Pune 19
20. Reading String from terminal
• Input function scanf can be used with %s format specification to
read in a string of characters.
• Example: char address[10]; scanf(“%s”, address);
• The scanf function automatically terminates the string that is read
with a null character.
• %ws format specification can be used for reading a specified
number of characters from the input string.
• scanf with %s or %ws can ready only strings without whitespaces.
• C supports a format specification known as the edit set conversion
code %[..] that can be used to read a line containing a variety of
characters, including whitespaces.
• Example:
char line[80];
scanf(“%[^n]”,line);
VIIT, Pune 20
21. Library functions
• There are various string handling functions define in
string.h some of them are:
VIIT, Pune 21
22. strlen()
• In C, strlen() function calculates the length of string.
• It takes only one argument, i.e, string name.
Syntax:
temp_variable = strlen(string_name);
• Function strlen() returns the value of type integer.
VIIT, Pune 22
23. strcpy()
• Function strcpy() copies the content of one string to the
content of another string.
• Syntax of strcpy()
strcpy(destination,source);
VIIT, Pune 23
24. strcat()
• concatenates(joins) two strings.
• resultant string is stored in the first string
specified in the argument.
Syntax of strcat()
strcat(first_string,second_string);
VIIT, Pune 24
25. strcmp()
• compares two string and returns value 0, if the two strings are
equal.
Syntax of strcmp()
temp_varaible=strcmp(string1,string2);
VIIT, Pune 25
26.
27. strlwr()
• function converts all the uppercase characters in that string to
lowercase characters.
• The resultant from strlwr() is stored in the same string.
Syntax of strlwr():-
strlwr(string_name);
VIIT, Pune 27
28. strupr()
• function converts all the lowercase characters in that string to
uppercase characters.
• The resultant from strupr() is stored in the same string.
Syntax of strupr()
strupr(string_name);
VIIT, Pune 28
29. Structure in C
– Introduction to structure
• Definition
• declaration of structure, declaration of structure variables
• initialization,
• accessing members of structure
• Array of structures
Vishwakarma Institute of Information
Technology
29
30. What is structure
• Structure is user defined data type which allows to combine
data items of different kinds
• Structures are used to represent a record
• For example to keep track of books in a library, following
attributes about each book has to maintained−
– Book ID (Data Type – Int)
– Title (Data Type – Char)
– Author (Data Type – Char)
– Publication (Data Type – Char)
– Price (Data Type – Float)
Vishwakarma Institute of Information
Technology
30
31. – Details about individual book such as its Book Id ,Title
,Author, Publication and Price form a single book record
BookId Title Author Publication
Single Book Record
Price
Vishwakarma Institute of Information
Technology
31
32. struct Book
{
int BookId;
char Title[20];
char Author[20];
char Publication[20];
float Price;
};
Members
OR Fields
of Structure
struct
keyword
tag OR structure
tag
Vishwakarma Institute of Information
Technology
32
Defining Structure
33. Declaration of structure variable
struct Book mybook;
OR
struct Book
{
int BookId;
char Title[20];
char Author[20];
char Publication[20];
float Price;
}mybook;
Variable of type Book
Variable of type Book
Vishwakarma Institute of Information
Technology
33
36. • To define a structure, struct keyword is used. The struct
statement defines a new data type, with more than one member
• The structure tag is optional and each member definition is a
normal variable definition, such as int i or float f or any other
valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or
more structure variables but it is optional
Vishwakarma Institute of Information
Technology
36
37. Structure Initialization
struct Book book1={0012,”C Programming”, ”Yashwant Kanetkar”, ”BPB
Publication”, 235.50};
Vishwakarma Institute of Information
Technology
37
38. Accessing Structure Members
• To access any member of a structure, member access
operator (.) is used. The member access operator is coded as a period
between the structure variable name and the structure member that is to be
accessed. Use the keyword struct to define variables of structure type
Vishwakarma Institute of Information
Technology
38
39. Example:-
Vishwakarma Institute of Information
Technology
39
#include <stdio.h>
#include <string.h>
struct Book
{
int BookId;
char Title[50];
char Author[50];
char publication[100];
float price;
};
40. int main( )
{
struct Book Book1; /* Declare Book1 of type Book */
struct Book Book2; /* Declare Book2 of type Book */
/* book 1 specification */
Book1.BookId=0012;
strcpy( Book1.Title, "C Programming");
strcpy( Book1.Author, "Nuha Ali");
strcpy( Book1.Publication, “BPB Publication");
Book1.Price = 649.50;
/* book 2 specification */
Book2.BookId=2314;
strcpy( Book2.Title, "Telecom Billing");
strcpy( Book2.Author, "Zara Ali");
strcpy( Book2.Publication, “Prentice Hall");
Book2.Price= 1234.80;
return 0;
}
Vishwakarma Institute of Information
Technology
40
41. Array of structures
#include <stdio.h>
#include <string.h>
struct Book
{
int BookId;
char Title[20];
char Author[20];
char Publication[20];
float Price;
};
int main( )
{
struct Book Books[10];
}
Vishwakarma Institute of Information
Technology
41
42. 0012
Computer Organization
William Stallings
Prentice Hall
980.00
Books[0]
0986
Fundamentals of Digital Circuits
A. Anand Kumar
PHI Learning
450.00
Books[1]
9876
Database System Concepts
Silberschatz, Korth ,Sudarshan
Mc Graw Hill
999.00
Books[2]
. .
. .
8876
Test Your C Skills
Yashwant Kanitkar
BPB Publications
248.00
Books[9]
Vishwakarma Institute of Information
Technology
42
43. BookId Title Author Publication Price
Books[0
]
BookId Title Author Publication Price
Books[1
]
BookId Title Author Publication Price
Books[2
]
BookId Title Author Publication Price
Books[3
]
BookId Title Author Publication Price
Books[4
]
BookId Title Author Publication Price
Books[5
]
BookId Title Author Publication Price
Books[6
]
BookId Title Author Publication Price
Books[7
]
BookId Title Author Publication Price
Books[8
]
BookId Title Author Publication Price
Books[9
]
Vishwakarma Institute of Information Technology
43
44. Struct inside another struct
Structure 1:
struct stud_address
{
int street;
char state[20];
char city[20];
char country[20];
} ;
Structure 2:
struct stud_data
{
int stud_id;
int stud_age;
char stud_name[20];
struct stud_address studentAddress;
};
Vishwakarma Institute of Information
Technology
44
45. struct stu_data mydata = {123, 25, “Chaitanya”, {55,“UP”, “Delhi”,
“India”}}
Initializing Structure Variable mydata
Vishwakarma Institute of Information
Technology
45
46. • typedef can also be used to give a name to user defined data types . For
example, typedef can be used with structure to define a new data type and
then use that data type to define structure variables directly as follows −
Vishwakarma Institute of Information
Technology
46
47. #include <stdio.h>
#include <string.h>
typedef struct Book
{
int BookId;
char Title[20];
char Author[20];
char Publication[20];
float Price;
};
Vishwakarma Institute of Information
Technology
47
48. Vishwakarma Institute of Information
Technology
48
#include<stio.h>
#include<string.h>
int main( )
{
Book book;
book.BookId=0012;
strcpy( book.Title, "C Programming");
strcpy( book.Author, "Nuha Ali");
strcpy( book.Publication, “BPB Publication");
book.Price = 649.50;
printf( "Book Id : %dn", book.Book_Id);
printf( "Book Title : %sn", book.Title);
printf( "Book Author : %sn", book.Author);
printf( "Book Publication : %sn", book.Publication);
printf( "Book Price : %dn", book.Price);
return 0;
}
49. When the above code is compiled and executed, it produces the following
result −
Book Id : 0012
Book title : C Programming
Book Author : Nuha Ali
Book Publication subject : BPB Publication
Book Price : 649.50
Vishwakarma Institute of Information
Technology
49
50. typedef vs #define
• #define is a C-directive which is also used to define the aliase for various
data types similar to typedef but with the following differences −
– typedef is limited to giving symbolic names to types only where as
#define can be used to define alias for values as well, e.g. you can
define 1 as ONE etc
– typedef interpretation is performed by the compiler whereas #define
statements are processed by the pre-processor
Vishwakarma Institute of Information
Technology
50
51. #include <stdio.h>
#define TRUE 1
#define FALSE 0
int main( )
{
printf( "Value of TRUE : %dn", TRUE);
printf( "Value of FALSE : %dn", FALSE);
return 0;
}
When the above code is compiled and executed, it produces the
following result:-
Value of TRUE : 1
Value of FALSE : 0
Vishwakarma Institute of Information
Technology
51
52. Analysis and Design of Algorithms
Searching Algorithm is an algorithm made up of a
series of instructions that retrieves information stored
within some data structure, or calculated in the search
space of a problem domain.
53. Linear Search is a method for finding a target value within a
list.
It sequentially checks each element of the list for the target
value until a match is found or until all the elements have been
searched.
Analysis and Design of
Algorithms
54. Algorithm:
Step1: Start from the leftmost element of array
and one by one compare x with each
element of array.
Step2: If x matches with an element, return the
index.
Step3: If x doesn’t match with any of elements,
return -1.
Analysis and Design of
Algorithms
55. Assume the following Array:
Search for 9
Analysis and Design of
Algorithms
8 12 5 9 2
60. Found at index = 3
Analysis and Design of
Algorithms
8 12 5 9 2
61. Time Complexity: O(n)
Analysis and Design of
Algorithms
Example of worst case: search for the last
element
4 6 8 9 1
62. #include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in arrayn");
scanf("%d", &n);
printf("Enter %d integer(s)n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to searchn");
scanf("%d", &search);
for (c = 0; c < n; c++)
63. Binary Search is the most popular Search algorithm.
It is efficient and also one of the most commonly used
techniques that is used to solve problems.
Binary search use sorted array by repeatedly dividing the search
interval in half.
Analysis and Design of
Algorithms
64. Algorithm:
Step1: Compare x with the middle element.
Step2: If x matches with middle element, we return
the mid index.
Step3: Else If x is greater than the mid element,
search on right half.
Step4: Else If x is smaller than the mid element.
search on left half.
Analysis and Design of
Algorithms
65. Assume the following Array:
Search for 40
Analysis and Design of
Algorithms
2 3 10 30 40 50 70
71. #include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elementsn");
scanf("%d",&n);
printf("Enter %d integersn", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter value to findn");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (array[middle] < search)
72. first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d.n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.n", search);
return 0;
}
74. Analysis and Design of
Algorithms
Sorting Algorithms:
Sorting — arranging items in order — is the most
fundamental task in computation.
Types of sorting:
1. Selection sort
2. Bubble sort ( slowest algorithm)
3. Insertion sort
4. Merge sort
5. Quick sort (fastest algorithm)
6. Heap sort
7. Radix sort
75. Analysis and Design of
Algorithms
Selection sort is to repetitively pick up the smallest element and
put it into the right position
• Find the smallest element, and put it to the first position.
• Find the next smallest element, and put it to the second position.
• Repeat until all elements are in the right positions.
76.
77. Analysis and Design of
Algorithms
The following tracks the code on an array with elements {38, 27, 43, 3, 9, 82, 10}.
78. Analysis and Design of
Algorithms
Disadvantage:
• Running time depends only slightly on the
amount of order in the file
79. #include <stdio.h>
int main()
{
int array[100], n, c, d, position, swap;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d integersn", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
position = c;
for ( d = c + 1 ; d < n ; d++ )
{
80. if ( array[position] > array[d] ) position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("Sorted list in ascending order:n");
for ( c = 0 ; c < n ; c++ )
printf("%dn", array[c]);
return 0;
81. Bubble Sort:
Bubble sort repetitively compares adjacent pairs of elements and
swaps if necessary.
• Scan the array, swapping adjacent pair of elements if they
are not in relative order. This bubbles up the largest element
to the end.
• Scan the array again, bubbling up the second largest
element.
• Repeat until all elements are in order.
82. The following tracks the code on an array with elements {38, 27, 43, 3, 9, 82, 10}
for three rounds of bubbling.
83.
84. #include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d integersn", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
85. if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:n");
for (c = 0; c < n; c++)
printf("%dn", array[c]);
return 0;
}
86. Analysis and Design of
Algorithms
Insertion sort maintains a sorted sub-array, and repetitively
inserts new elements into it. The process is as following:
• Take the first element as a sorted sub-array.
• Insert the second element into the sorted sub-array (shift
elements if needed).
• Insert the third element into the sorted sub-array.
• Repeat until all elements are inserted.
87. Analysis and Design of
Algorithms
The following tracks the code on an array with elements {38, 27, 43, 3, 9, 82, 10}.
88. Analysis and Design of
Algorithms
To insert 12, we need to make room
for it by moving first 36 and then 24.
93. #include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d integersn", n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
}
for (c = 1 ; c <= n - 1; c++)
{
d = c;
94. while ( d > 0 && array[d-1] > array[d])
{
t = array[d];
array[d] = array[d-1];
array[d-1] = t; d--;
}
}
printf("Sorted list in ascending order:n");
for (c = 0; c <= n - 1; c++)
{
printf("%dn", array[c]);
}
return 0;
}
95. Analysis and Design of
Algorithms
Advantages
Good running time for “almost sorted” arrays (n)
Disadvantages
(n2) running time in worst and average case
n2/2 comparisons and exchanges
96. Analysis and Design of
Algorithms
How to analyze program?
• The analysis of the program does not mean simply working
of the program but to check whether for all possible
situations programs works or not.
•The analysis involves working of the program efficiently.
• Efficiency in the sense:
The program requires less amount of storage space.
The program get executed in very less amount of time.
For three different cases of the time complexity.
1. Big-Oh OR Oh notation denoted as ‘O’.
2. Omega notation denoted as ‘Ω’.
3. Theta notation denoted as ‘Ө’.
97. Time Complexity:
Time required for execution of the program cannot computed in
the terms of Seconds because if the following factor:
1. Hardware of the machine.
2. Amount of time required by each machine instruction.
3. Amount of the time required by the compiler to execute the
instruction.
4. Instruction set.
Hence we assume that time required by the program to
execute means the total number of times the statements get
executed. The number of times the statement executing is
known as frequency count
98. Analysis and Design of
Algorithms
Example 1:
main()
{
int i,n,a=1;
printf(“|n Enter the value of Number=”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
a=a+5;
}
99. Analysis and Design of
Algorithms
Analysis:
• Printf() ans scanf() will be executed once
• i=0 will executed once.
• i<n will executed n times when i is less than n.
• i++ will execute n times.
• a=a=5 will execute n-1 times.
Summarize:
• Above steps i.e. 3n+2.
• But while denoting its time complexity we consider only the
order of magnitude hence we will neglect all the constants and
the terms becomes equal to n.
Therefore time complexity will be given as O(n).
100. Time Complexity of Binary Search O(log n):
When we say the time complexity is log n, we actually mean log2 n,
although the base of the log doesn't matter in asymptotic notations, but
still to understand this better, we generally consider a base of 2.
Let's first understand what log2(n) means.
101. Sr No. Expression log2(n) n output
1. log2(2^1) = 1 n = 2 1
2. log2(2^2) = 2 n = 4 2
3. log2(2^3) = 3 n = 8 3
4. log2(2^8) = 8 n = 256 8
Analysis and Design of
Algorithms
Time Complexity of Binary Search O(log n):
When we say the time complexity is log n, we actually
mean log2 n, although the base of the log doesn't matter in
asymptotic notations, but still to understand this better, we
generally consider a base of 2.
102. Analysis and Design of
Algorithms
It will be easier for us to relate it with the time complexity
of the binary search algorithm and also to understand
103. Analysis and Design of
Algorithms
• Suppose the input array has n elements.
• The outer loop runs n-1 rounds, roughly one for each position.
• Inside each outer loop, the inner loop goes through the
unsorted part of the array.
• On average, each inner loop scans through n/2 elements.
• The total time is roughly t(n) = (n – 1) * (n/2) *k = O(n^2),
where k denotes the number of basic operations inside each
inner loop; the constants are absorbed in the big-Oh notion.
• Note that in the big-Oh notion, we only care about the
dominating factor (which is n^2 in this case).