Unit - 3 - Arrays Strings

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 76

D.

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,

Two Dimensional and Multidimensional Arrays.

2
INTRODUCTION
D. Naga Jyothi

• The variables used so far can hold a single value at a time. int a; char ch;

Ex1- print the values of two input numbers


main()
{
int a,b;
scanf(“%d %d “, &a,&b);
printf(“a=%d,b=%d”,a,b);
}
This is easy to write.
Ex2- print the values of 100 input numbers
difficult to declare 100 variables and unable to remember all the variable names.
To overcome such problems Arrays are introduced.
D. Naga Jyothi

ARRAYS
4

Arrays are used to store huge quantities of data of same type by


using single variable.
Ex- used to store n integer numbers.
stores n float numbers etc..
DEFINITION OF ARRAY
D. Naga Jyothi

5  Array- array is an ordered collection of homogenous elements stored


contiguously in memory under the same name.
 Array- it is a collection of homogeneous elements.
 Array is an ordered - all the elements grouped sequentially ( 0,1,2,3…..)
 Homogenous - all the elements in the array must be similar in their type.
 HOW TO CREATE AN ARRAY
 Before we create an array, we need to decide on two properties:
 Element type: what kind of data will your array hold? ints, double,
chars? Remember, we can only choose one type.
 Array size: how many elements will your array contain?
 Once you specify the array size it cannot be changed during execution of
the program. In other words, we can change the size of an array at compile
time, but cannot change it at run-time.
• USING ARRAYS IN C
D. Naga Jyothi

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

1. ONE DIMENSIONAL ARRAYS


7

One dimensional array is a linear list consisting of related and


similar data items.
 In memory all the data items are stored in contiguous memory
locations one after the other.
 syntax
Datatype array_name[size];

Ex- int a[10];


created an array of 10 integers
float x[5];
created an array of 5 floating point values
double z[8];
created an array of 8 double values.?
Array elements are accessed using subscript specified in
square brackets [ ]
subscript ranges from 0 to arraysize-1
D. Naga Jyothi

Initializing One Dimensional Arrays


If array is not initialized it contain garbage values.

Four Types of array initializations:

Option 1: Initializing all memory locations

Option 2: Initialization without size

Option 3: Partial array initialization

Option 4: Initializing an entire array with zero.

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]

• 1000 1002 1004 1006 1008 Address


• Figure: Storage Representation of array
D. Naga Jyothi

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.

x[0] x[1] x[2] x[3] x [4]

1000 1002 1004 1006 1008 Address


Figure: Storage Representation of array
D. Naga Jyothi

• Option 3 Partial Array Initialization


11

• If the number of values to be initialized is less than the size of the


array, then the elements are initialized in the order from 0th
location. The remaining locations will be initialized to zero
automatically.
• int x[5]={75,79,82};
• Even though compiler allocates 5 memory locations, using this
declaration statement, the compiler initializes first three locations
x[0] x[1] x[2] x[3] x [4]
with 75,70 and 82,the next set of memory locations are
automatically initialized to 0’s by the compiler as shown in figure
1000 1002 1004 1006 1008 Address
Figure: Storage Representation of array
D. Naga Jyothi

12 • Option 4 Initializing an entire array with zero


• If you do not know any data ahead of time, but you
want to initialize everything to 0, just use 0 within { }.
• For example:
x[0] x[1] x[2] x[3] x [4]
• int x [5] = {0};
1000 1002 1004 1006 1008 Address
Figure: Storage Representation of array

For example:
int x [5] = {5};
x[0] x[1] x[2] x[3] x [4]

1000 1002 1004 1006 1008 Address


Figure: Storage Representation of array
HOW DO YOU ACCESS ARRAY ELEMENTS
D. Naga Jyothi

13

 To access an array element use name of the array with the


subscript in brackets.

 Array elements are accessed with subscript, the number in the


brackets following the array name.
 This number specifies the elements position in the array.
 The subscript would be 0,1,...... n-1.
 Ex- to access the temperature of 5th day.
 temperature[4]
D. Naga Jyothi
Accessing elements of one dimensional array(Cont…)
 To assign or store the value 89 for the 150th day:
temperature [149] = 89;

 You can loop through the elements of an array by varying the


subscript.
 To set all of the values to 0, say
for(i = 0;i < 365; i++)
temperature[i] = 0;

 You can not use assignment statement directly with arrays.


 If a[] , b[] are two arrays then the assignment a=b is not
valid.

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]‘.

 Note that for an array declared as int arr[5].


 The five values are represented as: arr[0] arr[1] arr[2] arr[3] arr[4]
and not arr[1] arr[2] arr[3] arr[4] arr[5]

 The first element of array always has a subscript of ’0′.

15
D. Naga Jyothi

16 // C program to read an array elements and find the sum of the


elements.
#include <stdio.h>
void main()
{ int a[10];
int i, SIZE, total=0;
printf(“\n Enter the size of the array : “);
scanf(“%d”,&size);
for (i = 0; i < SIZE ; i++)
scanf(“%d”,&a[i]);
for (i = 0; i < SIZE ; i++)
total += a[i];
printf("Total of array element values is %d\n", total);
getch();}
FEW IMPORTANT POINTS ABOUT THE ARRAY
D. Naga Jyothi

17

• 1. an array is a collection of similar elements.


• 2. the first element in the array is numbered from 0 to n-1.
• 3. while declaring an array we have to specify type and
size(dimension) of an array to the compiler.
• 4. how big an array all the elements are always stored in
contiguous memory location.
ARRAY OF CHARACTERS(STRING)
D. Naga Jyothi

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

• Whenever you want to store the tabular data use the


two dimensional array.
• Example- store the student name, rollno, and
attendance.
• The data must be in rows and columns.- matrix
• Declaration of two dimensional array
data type array_name[rows][columns];
2- DIMENSIONAL ARRAYS
D. Naga Jyothi

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

• They are stored in memory as


col0 col1 col2
Row0 [0][0] [0][1] [0][2]
Row1 [1][0] [1][1] [1][2]
Row2 [2][0] [2][1] [2][2]
D. Naga Jyothi

MEMORY MAP OF A 2-DIMENSIONAL ARRAY


24
Initializing 2D arrays
D. Naga Jyothi

•An array may be initialized at the time of declaration:


25

• 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

• C allows arrays of three or more dimensions.


• Syntax

Data type array_name[size1][size2]..[sizen];

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

MEMORY MAPPING OF THREE DIMENSIONAL


29

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

#include<stdio.h> int findMax(int x[],int size)


int findMax(int[],int); {
void main() int temp;
{ temp=x[0];
int a[10], n ,i , max; for(i=1;i<size; i++)
printf(“\n Enter the size of the array “); {
scanf(“%d”,&n); if(x[i]>temp)
printf(‘\n Enter the elements of the array : “); {
for(i=0;i<n;i++) temp=x[i];
scanf(“%d”,&a[i]); }
max=findMax(a, n); }
printf(“\n The Maximum value =%d”, max); return temp;
} }

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.

 It is the basic searching technique.


 Very easy to implement
 All array elements must be visited if the search fails.
 Could be very slow. – as it visited all the elements of array if element not
found
Example: Successful Linear Search
D. Naga Jyothi

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

Binary Search program in C


42
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0; last = n - 1; middle = (first+last)/2;
D. Naga Jyothi

43 while (first <= last) {


if (array[middle] < search)
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;
}
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

THE FOLLOWING TABLE SHOWS A TRACE OF HOW BUBBLE SORT WORKS.


45
BUBBLE SORT\EXCHANGE SORT
D. Naga Jyothi

• Suppose the list of numbers a[1],a[2],…,a[n] is in memory. The bubble sort


46
algorithm works as follows.
Step1- compare a[1] and a[2] and arrange them in the desired order, so that
a[1]<a[2].
then compare a[2] and a[3] and arrange them so that a[2]<a[3]. Then compare
a[3] and a[4] and arrange them so that a[3]< a[4]. Continue until we
compare a[n-1] with a[n] and arrange them so that a[n-1]<a[n].
- Observe that step-1 involves n-1 comparisons. when step-1 is completed a[n]
has the largest element in the list. The largest element is “bubbled up “ to the
nth position.
Step2- repeat step1 with one less comparison; it involves n-2 comparisions and
when step2 is completed the second largest element will occupy a[n-1].
Step3- repeat step1 with two fewer comparisons; involves n-3 comparisions.
Stepn-1. compare a[1] with a[2] and arrange them so that a[1]<a[2].
After n-1 steps, the list will be sorted in increasing order.
The process of sequentially traversing through all or part of the list is
frequently called a “pass”
BUBBLE SORT
D. Naga Jyothi

Suppose the following numbers are stored in an array: 32,51,27,85,66,23,13,57


47
Pass-1
32 51 27 85 66 23 13 57 no swap
32 27 51 85 66 23 13 57
32 27 51 85 66 23 13 57 no swap
32 27 51 66 85 23 13 57
32 27 51 66 23 85 13 57
32 27 51 66 23 13 85 57
32 27 51 66 23 13 57 85
Pass-2
27 32 51 66 23 13 57 85
27 32 51 66 23 13 57 85 no swap
27 32 51 66 23 13 57 85 no swap
27 32 51 23 66 13 57 85
27 32 51 23 13 66 57 85
27 32 51 23 13 57 66 85
and so on…
32 51 27 85 66 23 13 57
48 P1 - 32 27 51 66 23 13 57 85
P2 – 27 32 51 23 13 57 66 85
P3 – 27 32 23 13 51 57 66 85
P4 – 27 23 13 32 51 57 66 85
P5 – 23 13 27 32 51 57 66 85
P6 – 13 23 27 32 51 57 66 85
//C program to sort the numbers using bubble sort
D. Naga Jyothi
main() {
49 int arr[50],temp,i,j,n;
printf("\nEnter any Value less Than 50:");
scanf("%d",&n);

printf("\n\tEnter The Values into ARRAY: ");


for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=1;i<n;i++) {
for(j=0;j<n-i;j++) {
if(arr[j] >arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
} Output:
} Enter any Value less Than 50: 5
} Enter The Values into ARRAY: 1 5 0 3 2
printf(“\nSorted Series:"); Sorted Series: 0 1 2 3 5
for(i=0;i<n;i++) {
printf("\n %d",arr[i]);
}
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

51 SELECTION SORT PROGRAM IN C

#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

for(i = 0; i < n - 1; i++)


52 {
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%dn", a[i]);
return 0;
}
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];

 Size specifies no of characters in the array.


 When string stored into an array, compiler
• automatically insert null character ‘\n’at the
• end of the string.
• The size must be specified one extra space.
D. Naga Jyothi

54 INITIALIZATION OF STRINGS

• char name[10]= “hyderabad”;


or
• char name[10]= {‘h’,’y’,’d’,’e’,’r’,’a’,’b’,’a’,’d’,’\0’};
• When character array is initialized we must explicitly specify the null character.
• Character array initialized without specifying the size also.
• char name[]=“hyderabad”;
• Compiler automatically determines the size of this array based on the no of elements
initialized.
D. Naga Jyothi

55 STRING INPUT AND OUTPUT FUNCTIONS


• Strings can be read from the keyword and can be displayed onto the monitor using the following I/O
functions.
• Formatted Input Function-scanf ()
• The string can be read using the scanf function also. The format specifier associated with the string is %s.
• Scanf() function assigns the characters typed at keyboard to array until the enter key is pressed.

once enter key is pressed, scanf() places a ‘\0’ character


char name[10];
at the end of an array. Scanf(“%s”,name);
• Note – problem with the scanf() function is that it terminates
• input on the first white space it finds. So a string with multiple
• words are not accepted by the string.
• To read the multiple words of a string use another function gets().
D. Naga Jyothi

56 WRITING\ DISPLAY STRINGS ON TO A SCREEN

• 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

57 USE PUTS AND GETS FUNCTIONS

void main()
{
char name[30];
puts(“enter the string”);
gets(name);
puts(name);
}
D. Naga Jyothi

58 • Character I/O from Keyboard


• To read characters from the keyboard and write to screen it tkas the following form:
• variable_name = getchar( ); //reads one character
from the keyboard
• putchar(variable_name); // display the character on
the monitor
• here variable_name must of type char.
D. Naga Jyothi

• Program for testing character type using


59 getchar()

#include<stdio.h>

#include<ctype.h>

void main()

char ch;

Printf(“type any character”);

ch=getchar();

if(isalpha(ch))

printf(“\n the character is a letter”);

else

if(isdigit(ch))

printf(“the character is a digit); }


D. Naga Jyothi

60 Program to implement putchar(variable_name)


• #include<stdio.h>
• #include<ctype.h>
• void main()
• {
• char ch;
• printf(“\n enter an alphabet”);
• ch=getchar();
• if(islower(ch));
• putchar(toupper(ch));
• else
• putchar(tolower(ch));
• }
D. Naga Jyothi

61 PRINT A STRING USING LOOPS


/* Program to demonstrate printing of a string */
void main( )
{
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( i <= 7 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
D. Naga Jyothi

62 WITH THE HELP OF NULL CHARACTER


void main( )
{
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( name[i] != `\0' )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
D. Naga Jyothi

63 STRING MANIPULATION FUNCTIONS


• The C Library provides a rich set of string handling functions that are placed under the header file
<string.h>.

• Some of the string handling functions are:

• strlen() strcat() strcpy() strrchr()

• strcmp() strstr() strchr() strrev()

• Some of the functions in stdlib.h file are:

• malloc() calloc() realloc() free()

• Some of the functions in ctype.h file are:

• toupper() tolower() toascii()


D. Naga Jyothi

strlen () function: This function counts and returns the number of


64 characters in a string. It takes the form
Syantax: int n=strlen(string);
Where n is an integer variable, which receives the value of the
length of the string. The counting ends at the first null character.
D. Naga Jyothi

STRING HANDLING FUNCTIONS(Contd…)


65
• strcat () function:

• The strcat function joins two strings together.

• It takes of the following form:

strcat(string1,string2);

• string1 and string2 are character arrays.

• When the function strcat is executed, string2 is appended to string1.

• 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”);

• C permits nesting of strcat functions. Example:

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.

• It takes the following form:

• strcmp(str1,str2);

• returning value less than 0 means ''str1'' is less than ''str2'‘

• returning value 0 means ''str1'' is equal to ''str2'‘

• returning value greater than 0 means ''str1'' is greater than ''str2''

• string1 and string2 may be string variables or string constants.

• Example: strcmp(name1,name2);

• strcmp(name1,”John”);

• strcmp(“their” ,”there”);
D. Naga Jyothi

69
D. Naga Jyothi

70
D. Naga Jyothi

71 STRING HANDLING FUNCTIONS(Contd…)


strcpy () function: It copies the contents of one string to another string.
• It takes the following form: strcpy(string1,string2);
• The above function assign the contents of string2 to string1.
• string2 may be a character array variable or a string constant. Example:
• strcpy(city ,”Delhi”);

strcpy(city1,city2);

• strrev() function: Reverses the contents of the string.


• It takes of the form

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

STRING HANDLING FUNCTIONS(Contd…)


74 strstr () function:
It is a two-parameter function that can be used to locate a sub-string in a string.
It takes the form:

strstr (s1, s2);

Example: strstr (s1,”ABC”);


The function strstr searches the string s1 to see whether the string s2 is contained in s1.If yes, the
function returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL
pointer.

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

75 /*Define functions- length of a string, copy, concatenate, convert into


uppercase letters, compare two strings for alphabetical order- over strings
and implement in a program*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main() {
char str1[15],str2[15];
int n,c,len;
printf("\n Enter the string1 ");
gets(str1);
printf("\n Enter the string2 ");
gets(str2);
printf("\n***************************");
printf("\n 1. String Length ");
printf("\n 2. String Copy ");
printf("\n 3. String Comparison ");
printf("\n 4. String Concat ");
printf("\n***************************");
D. Naga Jyothi

printf("\n Enter the choice u want to perform");


76 scanf("%d",&n);
switch(n) {
case 1: len=strlen(str1);
printf("\n The length of the string entered is %d",len);
break;
case 2: strcpy(str1,str2);
printf("\n 1st string =%s,2nd string=%s",str1,str2);
break;
case 3: c=strcmp(str1,str2);
if(c==0)
printf("\n Both are equal");
else
printf("\n Both are different");
break;
case 4: printf("\n The resultant string is: %s",strcat(str1,str2));
break;
default: printf("\n Enter correct choice"); }}

You might also like