ARRAYS & STRING
OPERATIONS
1
Instructor
Dhiviya Rose J , AP-Sr. Scale | SoCSE
Recap
2
Variables Vs Array
3
int a,b;
a=10;
b=20;
c=30;
int marks[5];
marks[0]=51;
marks[1]=62;
marks[2]=43;
marks[3]=74;
marks[4]=55;
Index
Definition of Arrays.
Types of Arrays (1-D and 2-D)
1-D Arrays:
-Array Declaration.
-Accessing Elements of an array.
-Entering Data into an array.
-Reading data from an array.
-Array Initialization.
-Array Elements in Memory.
4
Introduction
• Arrays
• Structures of related data items
• Static entity – same size throughout program
• Derived data types
• Group of consecutive memory locations
• Same name and data type
5
• To refer to an element, specify
▫ Array name
▫ Position number/ Index
• Format:
arrayname[ position number ]
▫ First element at position 0
▫ n element array named c:
 c[ 0 ], c[ 1 ]...c[ n – 1 ]
6
Name of array
(All elements of
the array have
the same name, c)
Position number
or Index of the
element within
array c
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
7
int marks[5];
marks[0]=51;
marks[1]=62;
marks[2]=43;
marks[3]=74;
marks[4]=55;
Array Name= ?
Array Size=?
Index Range=?
No of Elements in the Array=?
Characteristics of Array
8
• Array elements are like normal variables
c[0] = 3;
printf( "%d", c[0] );
▫ Perform operations in subscript.
c[0] = 10;
C[1] = 20;
C[2] = c[0] + c[1]
printf( “%d”, c[2] );
9
Types of Arrays
• One Dimensional Array (1D)
• Two Dimensional Array (2D)
• Multi Dimensional Array
10
Declaring Arrays – 1D
• When declaring arrays, specify
• Name
• Type of array
• Number of elements
arrayType arrayName[ numberOfElements ];
• Examples:
int c[10];
float myArray[20];
11
Initializing Arrays – 1D
• Initializers
int n[5] = { 1, 2, 3, 4, 5 };
▫ If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
 All elements 0
▫ If too many a syntax error is produced syntax error
▫ C arrays have no bounds checking
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
▫ 5 initializers, therefore 5 element array
12
Initializing at Run time - scanf
void main()
{
int ans,myarr[2];
printf(“Enter the myarr[0]”);
scanf(“%d”,&myarr[0];
printf(“Enter the myarr[1]”);
scanf(“%d”,&myarr[1];
ans=myarr[0]+myarr[1];
printf(“The added answer is %d”,ans);
}
13
Accessing elements array using for– 1D
14
MULTI DIMENTIONALARRAY
15
Problem – Data Type???
• Class of 4 students
• Each student has 4 test scores
17
?????????????
Name varies……..
Instead of A[7]
given as A[2][0]
Solution( C Program representation)
• Represents this information in a two-dimensional array in
C program
• First dimension - student
• which student 0, 1, 2, 3
• Second dimension - marks
• which test score 0, 1, 2,3
18
19
Student 1
Student 2
Student 3
Student 4
M1 M2 M3 M3
Declaring a 2D Array
• Example:
int grades[4][4];
Creating a 2D Array
• Create array elements by telling how many ROWS and COLUMNS
• Example:
int grades[4][4];
• grades is a two-dimensional array,
• 4 rows and 4 columns
• One row for each student. One column for each test.
C arrays are row major, which means that we always refer to the row first.
Initializing Elements
// First student scores
grades[0][0] = 78;
grades[0][1] = 83;
grades[0][2] = 82;
Write assignment statements to fill-in the rest of the
array.
Declaration & Initialize 2D Arrays
• Example:
int grades[3][3] ={ { 78, 83, 82 },{ 90, 88, 94 },
{ 71, 73, 78 } };
• A Two-D Array is an array of arrays.
• Each row is itself a One-D array.
Multiple-Dimentional Arrays
• Initialization
• int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
• Initializers grouped by row in braces
• If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
• Referencing elements
• Row Specific & Column Specific
• Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
24
1 2
3 4
1 0
3 4
Row, Column Indices
78 83 82
90 88 94
71 73 78
97 96 95
89 93 90
Give both the ROW and COLUMN indices to pick out an individual element.
The fourth student’s third test score is at ROW 3, COLUMN 2
0
1
2
3
4
0 1 2
Exercise: Average Overall
• Find the average test score of all students’ test scores.
• Get the marks from the user
• Array name grades[4][4]
Exercise: Average Overall
int sum = 0;
int r,c;
for(r = 0; r < 4; r++)
for(c = 0; c < 4; c++)
sum = sum + grades[r][c];
Exercise:
Maximum Element in Matrix
Find maximum in a 2D array
max = matrix[0][0];
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
if ( matrix[i][j] > max)
max = matrix[i][j];
Searching Arrays: Linear Search and
Binary Search
• Search an array for a key value
• Linear search
• Simple
• Compare each element of array with key value
• Useful for small and unsorted arrays
30
Linear Search
• Step through array of records, one at a time.
• Look for record with matching key.
• Search stops when
• record with matching key is found
• or when search has examined all records without success.
How Linear Search works
32
33
Case 1: Target
found
34
Case 1: Target NOT
found
Program
#include<stdio.h>
void main()
{
int a[10],i,target;
printf("Enter array value n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Which value to be search ->");
scanf("%d",&target);
/* Linear Search logic */
for(i=0;i<n;i++)
if(target==a[i])
{
printf(“Value found at %d”,i);
}
}
35
Advantages of Linear Search
• Don't have to sort the data we search.
• Works well if only search operation is minimum
• Not optimal in case of large amount of data
36
Binary Search
• Assume that we are give an array of records that is
sorted. For instance:
• an array of records with integer keys sorted from smallest to largest
(e.g., ID numbers), or
• an array of records with string keys sorted in alphabetical order
(e.g., names).
Binary Search
[ 0 ] [ 1 ]
Example: sorted array of integer keys. Target=7.
3 6 7 11 32 33 53
[ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ]
39
Binary Search Pseudocode
…
if(size == 0)
found = false;
else {
middle = index of approximate midpoint of array segment;
if(target == a[middle])
target has been found!
else if(target < a[middle])
search for target in area before midpoint;
else
search for target in area after midpoint;
}
…
Program
int result=-1;
int low=0;
int high=length-1;
int mid;
while( result==-1 && low<=high )
{ mid= low + ((high - low) / 2);
if( list[mid] == target )
result = mid;
else if( list[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
41
Other Searching Algorithms
• Interpolation Search
• Indexed Searching
• Binary Search Trees
• Hash Table Searching
• Grover's Algorithm
• Best-first
• A*
42
Sorting Arrays
▫ Important computing application
▫ Arrange in some order
▫ Sorting done to make searching easier
Sorting: an operation that segregates items into groups
according to specified criterion.
A = { 3 1 6 2 1 3 4 5 9 0 }
A = { 0 1 1 2 3 3 4 5 6 9 }
• The "simple" sorting algorithms are
• bubble sort
• selection sort
43
Bubble Sort
• Several passes through the array
• Successive pairs of elements are compared
 If increasing order (or identical ), no change
 If decreasing order, elements exchanged
▫ Repeat
44
45
5 elements
….
4 pass
…..
5th pass all sorted
46
Program
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
} } }
47
SELECTION SORT
• improves on the bubble sort
• only one exchange for every pass through the array
Working Principle
• looks for the smallest value/largest value as it makes a
pass
• after each pass, the smallest item/largest item is in the
correct place.
48
How it works
49
Other Sorting Algorithms
● Bubble Sort
● Selection Sort
● Insertion Sort
● Merge Sort
● Shell Sort
● Heap Sort
● Quick Sort
● Radix Sort
● Swap Sort
51
STRING & ITS OPERATIONS
52
Definition
• A sequence of characters is often referred to
as a character “string”.
• No explicit type, instead strings are maintained
as arrays of characters
• Representing strings in C
• stored in arrays of characters
• array can be of any length
• end of string is indicated by a delimiter, the zero
character ‘0’
Character Vs Strings
Will be
considered as
string
Will be
considered as
character array
char myarr[]={‘h’,’e’,’l’,’l’,’o’,’0’}; char myarr[]={‘h’,’e’,’l’,’l’,’o’};
String Declaration & Initialization
• A string constant is a sequence of characters enclosed in
double quotes.
char a[10]=“Hello”;
Or
char *colorPtr = "blue";
pointer
String Input
• Use %s field specification in scanf to read string
• Example:
char myarr[11];
scanf(“%s”,myarr);
56
Only the
name of the
string
Example
#include <stdio.h>
void main()
{
char LName[10];
char FName[10];
printf("Enter your name : ");
scanf("%s %s",LName,FName);
printf("Nice to meet you %s %sn“,FName,LName);
}
57
String Functions
• string functions are used for performing different string
tasks
• Functions come from the utility library string.h
• #include <string.h>
• Examples
strlen(str) - calculate string length
strcpy(dst,src) - copy string at src to dst
strcmp(str1,str2) - compare str1 to str2
58
Standard Library
• String handling library has functions to
• Manipulate string data
• Search strings
• Tokenize strings
• Determine string length
59
String Length
Syntax: int strlen(char *str)
returns the length (integer) of the string argument
Example:
char str1 = “hello”;
int a;
a=strlen(str1);
61
Function prototype Function description
char *strcpy( char *s1,
const char *s2 )
Copies string s2 into array s1. The value of s1 is
returned.
char *strncpy( char *s1,
const char *s2, size_t n )
Copies at most n characters of string s2 into array s1.
The value of s1 is returned.
char *strcat( char *s1,
const char *s2 )
Appends string s2 to array s1. The first character of
s2 overwrites the terminating null character of s1.
The value of s1 is returned.
char *strncat( char *s1,
const char *s2, size_t n )
Appends at most n characters of string s2 to array s1.
The first character of s2 overwrites the terminating
null character of s1. The value of s1 is returned.
String Comparison
Syntax:
int strcmp(char *str1, char *str2)
compares str1 to str2, returns a value based on the first character
they differ at:
Answer < 0 if 2 string are less than or equal to
> 0 if 2 string are greater than
= 0 if the two strings are equal
String Comparison (cont)
strcmp examples:
strcmp(“hello”,”hello”) -- returns 0
strcmp(“yello”,”hello”) -- returns value > 0
strcmp(“Hello”,”hello”) -- returns value < 0
strcmp(“hello”,”hello there”) -- returns value < 0
strcmp(“some diff”,”some dift”) -- returns value < 0
expression for determining if two strings s1,s2 hold the
same string value:
!strcmp(s1,s2)
String Comparison (ignoring case)
Syntax:
int strcasecmp(char *str1, char *str2)
similar to strcmp except that upper and lower case characters
(e.g., ‘a’ and ‘A’) are considered to be equal
int strncasecmp(char *str1, char *str2, int n)
version of strncmp that ignores case
String Concatenation
Syntax:
char *strcat(char *dstS, char *addS)
appends the string at addS to the string dstS (after dstS’s
delimiter)
returns the string dstS
can cause problems if the resulting string is too long to fit in dstS
char *strncat(char *dstS, char *addS, int n)
appends the first n characters of addS to dstS
if less than n characters in addS only the characters in addS
appended
always appends a 0 character
Copying a String
WAP to create 3 string variable ,
String1 = Happy
String2=New Year
Op1: join s1+s2
Op2: Copy s1 to s3

CSEG1001Unit 3 Arrays and Strings

  • 1.
  • 2.
  • 3.
    Variables Vs Array 3 inta,b; a=10; b=20; c=30; int marks[5]; marks[0]=51; marks[1]=62; marks[2]=43; marks[3]=74; marks[4]=55;
  • 4.
    Index Definition of Arrays. Typesof Arrays (1-D and 2-D) 1-D Arrays: -Array Declaration. -Accessing Elements of an array. -Entering Data into an array. -Reading data from an array. -Array Initialization. -Array Elements in Memory. 4
  • 5.
    Introduction • Arrays • Structuresof related data items • Static entity – same size throughout program • Derived data types • Group of consecutive memory locations • Same name and data type 5
  • 6.
    • To referto an element, specify ▫ Array name ▫ Position number/ Index • Format: arrayname[ position number ] ▫ First element at position 0 ▫ n element array named c:  c[ 0 ], c[ 1 ]...c[ n – 1 ] 6 Name of array (All elements of the array have the same name, c) Position number or Index of the element within array c c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4]
  • 7.
  • 8.
  • 9.
    • Array elementsare like normal variables c[0] = 3; printf( "%d", c[0] ); ▫ Perform operations in subscript. c[0] = 10; C[1] = 20; C[2] = c[0] + c[1] printf( “%d”, c[2] ); 9
  • 10.
    Types of Arrays •One Dimensional Array (1D) • Two Dimensional Array (2D) • Multi Dimensional Array 10
  • 11.
    Declaring Arrays –1D • When declaring arrays, specify • Name • Type of array • Number of elements arrayType arrayName[ numberOfElements ]; • Examples: int c[10]; float myArray[20]; 11
  • 12.
    Initializing Arrays –1D • Initializers int n[5] = { 1, 2, 3, 4, 5 }; ▫ If not enough initializers, rightmost elements become 0 int n[ 5 ] = { 0 }  All elements 0 ▫ If too many a syntax error is produced syntax error ▫ C arrays have no bounds checking • If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 }; ▫ 5 initializers, therefore 5 element array 12
  • 13.
    Initializing at Runtime - scanf void main() { int ans,myarr[2]; printf(“Enter the myarr[0]”); scanf(“%d”,&myarr[0]; printf(“Enter the myarr[1]”); scanf(“%d”,&myarr[1]; ans=myarr[0]+myarr[1]; printf(“The added answer is %d”,ans); } 13
  • 14.
    Accessing elements arrayusing for– 1D 14
  • 15.
  • 16.
    Problem – DataType??? • Class of 4 students • Each student has 4 test scores
  • 17.
  • 18.
    Solution( C Programrepresentation) • Represents this information in a two-dimensional array in C program • First dimension - student • which student 0, 1, 2, 3 • Second dimension - marks • which test score 0, 1, 2,3 18
  • 19.
    19 Student 1 Student 2 Student3 Student 4 M1 M2 M3 M3
  • 20.
    Declaring a 2DArray • Example: int grades[4][4];
  • 21.
    Creating a 2DArray • Create array elements by telling how many ROWS and COLUMNS • Example: int grades[4][4]; • grades is a two-dimensional array, • 4 rows and 4 columns • One row for each student. One column for each test. C arrays are row major, which means that we always refer to the row first.
  • 22.
    Initializing Elements // Firststudent scores grades[0][0] = 78; grades[0][1] = 83; grades[0][2] = 82; Write assignment statements to fill-in the rest of the array.
  • 23.
    Declaration & Initialize2D Arrays • Example: int grades[3][3] ={ { 78, 83, 82 },{ 90, 88, 94 }, { 71, 73, 78 } }; • A Two-D Array is an array of arrays. • Each row is itself a One-D array.
  • 24.
    Multiple-Dimentional Arrays • Initialization •int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; • Initializers grouped by row in braces • If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; • Referencing elements • Row Specific & Column Specific • Specify row, then column printf( "%d", b[ 0 ][ 1 ] ); 24 1 2 3 4 1 0 3 4
  • 25.
    Row, Column Indices 7883 82 90 88 94 71 73 78 97 96 95 89 93 90 Give both the ROW and COLUMN indices to pick out an individual element. The fourth student’s third test score is at ROW 3, COLUMN 2 0 1 2 3 4 0 1 2
  • 26.
    Exercise: Average Overall •Find the average test score of all students’ test scores. • Get the marks from the user • Array name grades[4][4]
  • 27.
    Exercise: Average Overall intsum = 0; int r,c; for(r = 0; r < 4; r++) for(c = 0; c < 4; c++) sum = sum + grades[r][c];
  • 28.
  • 29.
    Find maximum ina 2D array max = matrix[0][0]; for(int i = 0; i < r; i++) for(int j = 0; j < c; j++) if ( matrix[i][j] > max) max = matrix[i][j];
  • 30.
    Searching Arrays: LinearSearch and Binary Search • Search an array for a key value • Linear search • Simple • Compare each element of array with key value • Useful for small and unsorted arrays 30
  • 31.
    Linear Search • Stepthrough array of records, one at a time. • Look for record with matching key. • Search stops when • record with matching key is found • or when search has examined all records without success.
  • 32.
  • 33.
  • 34.
  • 35.
    Program #include<stdio.h> void main() { int a[10],i,target; printf("Enterarray value n"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Which value to be search ->"); scanf("%d",&target); /* Linear Search logic */ for(i=0;i<n;i++) if(target==a[i]) { printf(“Value found at %d”,i); } } 35
  • 36.
    Advantages of LinearSearch • Don't have to sort the data we search. • Works well if only search operation is minimum • Not optimal in case of large amount of data 36
  • 37.
    Binary Search • Assumethat we are give an array of records that is sorted. For instance: • an array of records with integer keys sorted from smallest to largest (e.g., ID numbers), or • an array of records with string keys sorted in alphabetical order (e.g., names).
  • 38.
    Binary Search [ 0] [ 1 ] Example: sorted array of integer keys. Target=7. 3 6 7 11 32 33 53 [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ]
  • 39.
  • 40.
    Binary Search Pseudocode … if(size== 0) found = false; else { middle = index of approximate midpoint of array segment; if(target == a[middle]) target has been found! else if(target < a[middle]) search for target in area before midpoint; else search for target in area after midpoint; } …
  • 41.
    Program int result=-1; int low=0; inthigh=length-1; int mid; while( result==-1 && low<=high ) { mid= low + ((high - low) / 2); if( list[mid] == target ) result = mid; else if( list[mid] < target) low = mid + 1; else high = mid - 1; } 41
  • 42.
    Other Searching Algorithms •Interpolation Search • Indexed Searching • Binary Search Trees • Hash Table Searching • Grover's Algorithm • Best-first • A* 42
  • 43.
    Sorting Arrays ▫ Importantcomputing application ▫ Arrange in some order ▫ Sorting done to make searching easier Sorting: an operation that segregates items into groups according to specified criterion. A = { 3 1 6 2 1 3 4 5 9 0 } A = { 0 1 1 2 3 3 4 5 6 9 } • The "simple" sorting algorithms are • bubble sort • selection sort 43
  • 44.
    Bubble Sort • Severalpasses through the array • Successive pairs of elements are compared  If increasing order (or identical ), no change  If decreasing order, elements exchanged ▫ Repeat 44
  • 45.
  • 46.
  • 47.
    Program /* Bubble sortingbegins */ for (i = 0; i < num; i++) { for (j = 0; j < (num - i - 1); j++) { if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } 47
  • 48.
    SELECTION SORT • improveson the bubble sort • only one exchange for every pass through the array Working Principle • looks for the smallest value/largest value as it makes a pass • after each pass, the smallest item/largest item is in the correct place. 48
  • 49.
  • 50.
    Other Sorting Algorithms ●Bubble Sort ● Selection Sort ● Insertion Sort ● Merge Sort ● Shell Sort ● Heap Sort ● Quick Sort ● Radix Sort ● Swap Sort
  • 51.
  • 52.
    STRING & ITSOPERATIONS 52
  • 53.
    Definition • A sequenceof characters is often referred to as a character “string”. • No explicit type, instead strings are maintained as arrays of characters • Representing strings in C • stored in arrays of characters • array can be of any length • end of string is indicated by a delimiter, the zero character ‘0’
  • 54.
    Character Vs Strings Willbe considered as string Will be considered as character array char myarr[]={‘h’,’e’,’l’,’l’,’o’,’0’}; char myarr[]={‘h’,’e’,’l’,’l’,’o’};
  • 55.
    String Declaration &Initialization • A string constant is a sequence of characters enclosed in double quotes. char a[10]=“Hello”; Or char *colorPtr = "blue"; pointer
  • 56.
    String Input • Use%s field specification in scanf to read string • Example: char myarr[11]; scanf(“%s”,myarr); 56 Only the name of the string
  • 57.
    Example #include <stdio.h> void main() { charLName[10]; char FName[10]; printf("Enter your name : "); scanf("%s %s",LName,FName); printf("Nice to meet you %s %sn“,FName,LName); } 57
  • 58.
    String Functions • stringfunctions are used for performing different string tasks • Functions come from the utility library string.h • #include <string.h> • Examples strlen(str) - calculate string length strcpy(dst,src) - copy string at src to dst strcmp(str1,str2) - compare str1 to str2 58
  • 59.
    Standard Library • Stringhandling library has functions to • Manipulate string data • Search strings • Tokenize strings • Determine string length 59
  • 60.
    String Length Syntax: intstrlen(char *str) returns the length (integer) of the string argument Example: char str1 = “hello”; int a; a=strlen(str1);
  • 61.
    61 Function prototype Functiondescription char *strcpy( char *s1, const char *s2 ) Copies string s2 into array s1. The value of s1 is returned. char *strncpy( char *s1, const char *s2, size_t n ) Copies at most n characters of string s2 into array s1. The value of s1 is returned. char *strcat( char *s1, const char *s2 ) Appends string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned. char *strncat( char *s1, const char *s2, size_t n ) Appends at most n characters of string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned.
  • 62.
    String Comparison Syntax: int strcmp(char*str1, char *str2) compares str1 to str2, returns a value based on the first character they differ at: Answer < 0 if 2 string are less than or equal to > 0 if 2 string are greater than = 0 if the two strings are equal
  • 63.
    String Comparison (cont) strcmpexamples: strcmp(“hello”,”hello”) -- returns 0 strcmp(“yello”,”hello”) -- returns value > 0 strcmp(“Hello”,”hello”) -- returns value < 0 strcmp(“hello”,”hello there”) -- returns value < 0 strcmp(“some diff”,”some dift”) -- returns value < 0 expression for determining if two strings s1,s2 hold the same string value: !strcmp(s1,s2)
  • 64.
    String Comparison (ignoringcase) Syntax: int strcasecmp(char *str1, char *str2) similar to strcmp except that upper and lower case characters (e.g., ‘a’ and ‘A’) are considered to be equal int strncasecmp(char *str1, char *str2, int n) version of strncmp that ignores case
  • 65.
    String Concatenation Syntax: char *strcat(char*dstS, char *addS) appends the string at addS to the string dstS (after dstS’s delimiter) returns the string dstS can cause problems if the resulting string is too long to fit in dstS char *strncat(char *dstS, char *addS, int n) appends the first n characters of addS to dstS if less than n characters in addS only the characters in addS appended always appends a 0 character
  • 66.
    Copying a String WAPto create 3 string variable , String1 = Happy String2=New Year Op1: join s1+s2 Op2: Copy s1 to s3