Unit - 3 - Arrays Strings
Unit - 3 - Arrays Strings
Unit - 3 - Arrays Strings
Naga Jyothi
UNIT- 3
ARRAYS
D. Naga Jyothi
UNIT-IV
Arrays:
Definition and declaration, Initialization, Accessing elements of
arrays, Storing values in arrays,
Inter-function Communication:
Passing individual elements,
Passing the whole array,
Array Applications:
Bubble Sort,
Sequential Search,
2
INTRODUCTION
D. Naga Jyothi
• The variables used so far can hold a single value at a time. int a; char ch;
ARRAYS
4
6
• In C, the arrays can be classified based on how the data items
are arranged for human understanding
• Arrays are broadly classified into three categories,
1. One dimensional arrays
2. Two dimensional arrays
3. Multi dimensional arrays
D. Naga Jyothi
8
D. Naga Jyothi
9
Option 1 Initializing all memory locations
If you know all the data at compile time, you can specify all your data within
brackets:
int x [5] = {75, 79, 82, 70, 68};
• during compilation, 5 contiguous memory locations are reserved by the compiler
for the variable x and all these locations are initialized as shown in Fig. If the
size of integer is 2 bytes, 10 bytes will be allocated for the variable X.
•
• x[0] x[1] x[2] x[3] x [4]
•
10
• Option 2 initialization without size
• If we omit the size of your array, but specify an initial set of
data, the compiler will automatically determine the size of your
array. This way is referred as initialization without size.
• int X [] = {75, 79, 82, 70, 68};
• the array size will be set of the total number of initial values
specified.
• Here, the compiler creates an array of 5 elements.
For example:
int x [5] = {5};
x[0] x[1] x[2] x[3] x [4]
13
14
Accessing elements of one dimensional array(Cont…)
//Example for accessing array elements.
D. Naga Jyothi
#include<stdio.h>
main() {
int arr[10];
int i ;
for(i=0;i<10;i++) {
arr[i] = i; // Initializing each element separately
}
int j = arr[5]; // Accessing the 5th element of integer array
arr //and assigning its value to integer 'j'.
printf(“Value at 5th location is: %d”,j);
}
As we can see above, the 5th element of an array is accessed as ‘arr[5]‘.
15
D. Naga Jyothi
17
18
• In c language array of characters are treated as character
string.
• The size in the character array represents the maximum number
of characters that the string can hold.
• For example: char name[6];
• Declares name as an character array (string) that can hold a
•Whenever compiler find array of
maximum of 6 characters. characters , it terminates with the
• “APPLE” A
additional character call it as null
character.
P • so name[5]- contains the null
P character.
•When declaring character arrays,
L
we must always use one extra
E space for the null character.
\0
• Initialization of character array
D. Naga Jyothi
19
• char name[]= {‘A’,’P’,’P’,’L’,’E’,’\0’};
• or char name[]=“APPLE”;- in this declaration compiler
automatically inserts the null character.
• Bound checking
• In c there is no check to see whether the subscript
This will lead to
used for an array exceeds the size of an array or not.
unpredictable results.
Ex- main()
{ There is no error
int x[50]; message from compiler
for(i=0;i<=60;i++)
{
x[i]=i;
}
}
TWO DIMENSIONAL ARRAYS
D. Naga Jyothi
20
21 • Example
• char names[3][4];
• in the above declaration
• char(dataType) specifies type of element in
each slot
• names(array_name) specifies name of the array
• [3](rows) specifies number of rows
• [4](cols) specifies number of columns
Row dimension is optional.
Initializing 2D arrays
D. Naga Jyothi
22
char names[3][4] = {
{ 'J', 'o', 'h', 'n'} ,
{ 'M', 'a', 'r', 'y'} ,
• An integer array may be
{ 'I', 'v', 'a', 'n'}
initialized to all zeros as follows:
};
int nums[3][4] = {0};
• This only works for zero.
nums[0][0] = 16;
• To access an element of a 2D
printf("%d", nums[1][2]);
array, you need to specify
both the row and the column: ...
'J' 4269
Address
'J' 'o' 'h' 'n' is stored: 'o' 4270
'M' 'a' 'r' 'y' 'h' 4271
'n' 4272
'M' 4273
• Two-dimensional arrays in C are stored in "row-major 'a' 4274
format": the array is laid out contiguously, one row at 'r' 4275
a time: 'y' 4276
...
D. Naga Jyothi
23
• int x[4][3]={
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
• int x[3][2]={1,2,3,4,5,6};
• int x[][2]={1,2,3,4,5,6};
• int x[2][]={1,2,3,4,5,6};
• int x[][]={1,2,3,4,5,6};
Never work
3. MULTIDIMENSIONAL ARRAY
D. Naga Jyothi
26
int a[3][4][2];
“an array of three arrays of four arrays of two
integers”
D. Naga Jyothi
THREE-DIMENSIONAL ARRAY
27
THREE-DIMENSIONAL ARRAY
D. Naga Jyothi
28
array of three Array of 4 rows and 2 columns
arrays
int arr[3][4][2] ={
{ { {
{ 2, 4 }, { 7, 6 }, { 8, 9 },
{ 7, 8 }, { 3, 4 }, { 7, 2 },
{ 3, 4 }, { 5, 3 }, 4 },
{ 5, 6 } { 2, 3 } { 5, 1 }
}, }, }
};
D. Naga Jyothi
ARRAY
/* write a c program to calculate the addition of two
D.matrices*/
Naga Jyothi
//addition of matrix
#include<stdio.h> for(i=0;i<m;i++)
30
void main() {
{ for(j=0;j<n;j++)
int m,n,i,j,a[5][5],b[5][5],c[5][5]; {
printf("\n enter the size - of the matrix\n"); c[i][j]=a[i][j]+b[i][j];
scanf("%d %d", &m,&n); }//forj
printf("enter the elements of matrix a\n"); }//for i
for(i=0;i<m;i++) //display resultant matrix
{ for(i=0;i<m;i++)
for(j=0;j<n;j++) {
{ for(j=0;j<n;j++)
scanf("%d", &a[i][j]); {
}//forj printf("%d\t",c[i][j]);
}//fori }
printf("\nenter the elements of matrix b\n"); printf("\n");
for(i=0;i<m;i++) }//fori
{
for(j=0;j<n;j++) }// main
{
scanf("%d",&b[i][j]);
}//forj
}//fori
/* Fill 2-d array, print out values, sum the array. */
D.#include
Naga Jyothi <stdio.h>
#define M 3 /* Number of rows */
31 #define N 4 /* Number of columns */
int main(void){
int a [ M ] [ N ], i, j, sum = 0;
for ( i = 0; i < M; ++i ) /* fill the array */
for (j = 0; j < N, ++j )
a [ i ] [ j ] = i + j;
for ( i = 0; i < M; ++i ){ /* print array values */
for (j = 0; j < N, ++j )
printf(“a [ %d ] [ %d ] = %d “, i, j, a[ i ] [ j ]);
printf (“\n”);
}
for ( i = 0; i < M; ++i ) /* sum the array */
for (j = 0; j < N, ++j )
sum += a[ i ] [ j ]; Produces the output:
printf(“\nsum = %d\n\n”); a[ 0 ] [ 0 ] = 0 a[ 0 ] [ 1 ] = 1 a[ 0 ] [ 2 ] = 2 a[ 0 ] [ 3 ] = 3
return 0; a[ 1 ] [ 0 ] = 1 a[ 1 ] [ 1 ] = 2 a[ 1 ] [ 2 ] = 3 a[ 1 ] [ 3 ] = 4
} a[ 2 ] [ 0 ] = 0 a[ 2 ] [ 1 ] = 3 a[ 2 ] [ 2 ] = 4 a[ 2 ] [ 3 ] = 5
sum = 30
PASSING ARRAYS AS ARGUMENTS TO FUNCTIONS
D. Naga Jyothi
32 • We can pass array elements as arguments to the called function in two ways
• 1. pass individual array elements
• 2. pass the entire array at a time
• 1. passing individual array elements.
• we can pass individual array elements to the called functions by either call
Call
by by value
value or call by reference. Call by reference
void main() void main()
{ {
int i; int i;
int int arr[]={10,20,30,40,50};
arr[]={10,20,30,40,50}; for(i=0;i<5;i++)
for(i=0;i<5;i++) display(&arr[i]);
display(arr[i]); getch();
}//main
}//main display( int *x)
display( int x) { printf(“%d”,*x);
{ printf(“%d”,x); }//display
}//display
2. PASS THE ENTIRE ARRAY AT A TIME
D. Naga Jyothi
33
• Fixed length array- the size of the array is known when
the program is written. int arr[10];// compile time
• Variable length array- the size of the array is known
when the program is run. int arr[];// run time
• If u want to pass the fixed length array as argument to
the called function, simply pass the array name to called
function. void display(int x[])
{
void display(int x[]); int i;
void main() for(i=0;i<5;i++)
{ {
int arr[5]={10,20,30,40,50}; printf(" %d",x[i]);
display(arr); }//for
}//main }//display()
D. Naga Jyothi
34
• In variable length array we have to pass array name as
well as size of the array to the called function.
void display(int arr[],int size); void display(int arr[],int size)
void main() {
{ int i;
int a[10]; for(i=0;i<size;i++)
int n,i; printf(" %d",arr[i]);
printf("\n enter the size of the array");
}
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
display(a,n);
Note- In c, the name of an array gives the
}//main
address of the first element in the array
//Program to read an array of elements and find max value.
D. Naga Jyothi
35
D. Naga Jyothi
APPLICATIONS OF ARRAY
36
1. Linear search
2. Bubble sort
Searching is the process of finding a particular element in an array.
Sorting is the process of rearranging the elements in an array so that
they are stored in some well-defined order
D. Naga Jyothi
37
Applications of Array
1. LINEAR SEARCH (SEQUENTIAL SEARCH ):
A linear or sequential search of an array begins from the first element of array
and continues until the item is found or the entire array has been searched.
38
//Program to find a number in the array using sequential search.
D. Naga Jyothi
main() {
39 int a[10],i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<n;i++) { Output:
if(a[i]==m) { Enter the size of an array: 5
c=1; Enter the elements of the array: 4 6 8 0 3
break; Enter the number to be search: 0
} The number is found
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
}
LINEAR SEARCH IMPLEMENTATION USING NON RECURSIVE
METHOD
#include <stdio.h>
/* Searches for an target in an array using
#define SIZE 8 Linear search;
* Returns index of target or -1 if not found */
int linear_search(int a[], int target, int size);
void read_array(int a[], int size); int linear_search(int a[], int target,
int size)
int main(void) { {
int x[SIZE], target; int i, found = 0, loc;
int index;
i = 0;
while (!found && i < size) {
read_array(x, SIZE);
if (a[i] == target)
printf("Enter Element to search for: ");
found = 1;
scanf(“%d", &target); else
index = linear_search(x, target, SIZE); ++i;
if (index != -1) }
printf("Target was found at index %d\n", index+1);
else if (found)
printf("Sorry, target item was not found"); loc = i;
getch();
else
loc = -1;
return 0;
}
return loc;
void read_array (int a[], int size) { }
int i;
printf("Enter %d integer numbers separated by blanks\n> ", size);
for (i = 0; i < size; ++i) 40
D. Naga Jyothi
scanf("%d", &a[i]);
D. Naga Jyothi
41 BINARY SEARCH
• Binary Search is a search algorithm that is used to find the position of an
element (target value ) in a sorted array. The array should be sorted prior to
applying a binary search.
• The binary search algorithm works by comparing the element to be searched by
the middle element of the array and based on this comparison follows the
required procedure.
• Case 1 − element = middle, the element is found return the index.
• Case 2 − element > middle, search for the element in the sub-array starting from
middle+1 index to n.
• Case 3 − element < middle, search for element in the sub-array starting from 0
index to middle -1.
D. Naga Jyothi
44 BUBBLE SORT
The idea of Bubble (or exchange) sort is to scan through the list and swap each
pair of adjacent elements that are not in order.
The process is repeated each time from index zero to one less than the previous
limit until either the list is exhausted or until a pass that involve no swap is
encountered.
At the end of first pass, the largest element will move (or bubble up) to the end
of the list.
At the end of the second pass , the second largest will move to its right place,
etc.
44
D. Naga Jyothi
50 SELECTION SORT
The selection Sort is an algorithm that works by a finding the smallest number from
the array and then placing it to the first position. The next array that is to be
traversed will start from index next to the position where the smallest number is
placed.
Example : let the list of numbers be 6, 3, 8, 12, 9
P1 – 3, 6, 8, 12, 9 //min=3 , so replaced in the first position
P2 - 3, 6, 8, 12, 9 // min = 6, should be placed in 2nd place, no change
P3 - 3, 6, 8, 12, 9 // min = 8, No change
P4 - 3, 6, 8, 9, 12 // min = 9, placed in 4th position
Thus we got the sorted list.
D. Naga Jyothi
#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elements");
scanf("%d", &n);
printf("Enter %d Numbers ", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
D. Naga Jyothi
53 STRINGS
• A string is an array of characters.
• A group of characters stored in an array is called string.
• Declaration
Char arry_name[size];
54 INITIALIZATION OF STRINGS
• We can use printf() function to display string on to a screen with %s format specifier.
In this case also printf() function cannot print the Printf(“%s”,name);
multiple words.
• To overcome this problem use puts() to display multiple
words.
• unlike printf() function, puts() places the cursor to the next line. \n is not necessary.
D. Naga Jyothi
void main()
{
char name[30];
puts(“enter the string”);
gets(name);
puts(name);
}
D. Naga Jyothi
#include<stdio.h>
#include<ctype.h>
void main()
char ch;
ch=getchar();
if(isalpha(ch))
else
if(isdigit(ch))
•
D. Naga Jyothi
strcat(string1,string2);
• It does so by removing the null character at the end of string1 and placing string2 from there.
• strcat function may also append a string constant to a string variable. The following is valid.
strcat(part1,”Good”);
strcat(strcat(string1,string2),string3);
D. Naga Jyothi
66
D. Naga Jyothi
67
68
STRING HANDLING FUNCTIONS(Contd…)
strcmp () function:
• The strcmp function compares two strings, it returns the value 0 if they are equal.
• If they are not equal, it returns the numeric difference between the first non matching characters in the strings.
• strcmp(str1,str2);
• Example: strcmp(name1,name2);
• strcmp(name1,”John”);
• strcmp(“their” ,”there”);
D. Naga Jyothi
69
D. Naga Jyothi
70
D. Naga Jyothi
strcpy(city1,city2);
strrev(string);
D. Naga Jyothi
72
• Example:
• #include<stdio.h>
• #include<string.h>
• void main(){
• char s[]=”hello”;
• strrev(s);
• puts(s);
• }
D. Naga Jyothi
73
D. Naga Jyothi
strchr() function:
It is used to determine the existence of a character in a string.
Example: strchr (s1,’m’); //It locates the first occurrence of the character ‘m’.
Example: strrchr(s2,’m’); //It locates the last occurrence of the character ‘m’.
D. Naga Jyothi