0% found this document useful (0 votes)
8 views

Unit - 3 Notes

Arrays allow storing multiple values of the same type under a single variable name. They initialize elements sequentially in contiguous memory locations. The document discusses one-dimensional arrays in C, including declaring, initializing, and accessing array elements using indexes starting from 0. It also explains the need for arrays with an example on calculating average age.

Uploaded by

Temp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit - 3 Notes

Arrays allow storing multiple values of the same type under a single variable name. They initialize elements sequentially in contiguous memory locations. The document discusses one-dimensional arrays in C, including declaring, initializing, and accessing array elements using indexes starting from 0. It also explains the need for arrays with an example on calculating average age.

Uploaded by

Temp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

UNIT III

ARRAYS AND STRINGS

Syllabus:

Arrays- Initialization – Declaration One dimensional and Two dimensional arrays. String – String Operations –
String Arrays. Simple Programs – Sorting – Searching – Matrix Operations.

Introduction:

3. ARRAYS AND STRINGS

3.1 Arrays

We can start with an example

#include<stdio.h>
#include<conio.h>
void main()
{
int mark1,mark2,mark3,mark4,mark5,tot;
clrscr();
printf("Enter the five subject marks of a student ");
scanf("%d %d %d",&mark1,&mark2,&mark3,&mark4,&mark5);
tot = mark1+mark2+mark3+mark4+mark5;
printf("Total = %d",tot);
}

Explanation

We have to obtain marks of five different and so we are using five different varaibles to obtain the marks.

Problem:

For example, consider a wild scenario where we have to obtain the marks of 100 different subjects.How we
could acheive this?

Solution :

There are two possible solution.

1. Use 100 variables each holding value of a subject.

We have to use 100 varibles like mark1, mark2, mark3, mark4,............., mark100.

2. Use 1 variable which can hold marks of 100 different subjects.

We will use an array variable like mark[100].

Array is a variable capable of holding more than 1 value at a time.

3.1.1 Introduction

 An Array is a variable which can hold more than 1 value at a time.

 An array is just an identifier to store a set of data with common name. The same rules used to name a
variable is applicable for array varibles also.

 Array can is the collection of interrelated data.

 Array is a collection or group of similar data type elements stored in contiguous memory.

 Array is a derived data type that is used to store elements in contiguous memory location. Derived
data type is nothing but a data type formed from the primary data type.

 Array can be also called as collection of homogeneous data.

There are three different types of array in C

1. Single Dimensional Array. (1D)

2. Two dimensional Array and (2D)

3. Multi Dimensional Array.

3.1.2 Declaring an Array

Syntax

Data-Type ArrayName[index];

or
Storage_Class Data_Type ArrayName[index]

Data type - mentions which type of value should be stored in an array

Index - specifies how many values should be stored i.e. size.

Example of declaring array

int a[10] // data type  integer size  10

char a[50] // data type  character size  50

float a[100] // data type  floating point size  100

float a[100] means that ,it can store 100 floating point values in contiguous memory location.

Consider the example

int age[5];

Array element age[0] age[1] age[2] age[3] age[4]

Memory location 1010 1012 1014 1016 1018

Interprations to be made from the above example:

 The array age has five integer elements such as age[0], age[1], age[2], age[3], age[4].

 The first element of array is numbered 0. i.e. age[0]. An array index always starts from zero.

 Array index starts with 0 and ends with n-1. Where n is an size of an Array.

 The size of array age is 10 bytes.i.e five times the size of integer, becuase the integer requires two bytes
and there are 5 integer elements in the array age.

 The starting adress of array age is 1010 and the address of next element is 1012 and not 1011,because an
integer requires 2 bytes of memory, so both the address bytes 1010 and 1011 will be occupied by the
first element age[0] itself.

Initializing an array:

There are two possible ways to initialize an array.

1. An array can be initialized by specifying the index.


int marks[10]={65,68,47,87,89};

In the above example an array of size 20 bytes (10 elements each requiring 2 bytes.) will be allocated. In other
words an array with a memory to hold 10 integer variables will be created.

The value will be initialized as follows

Array
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]
elements

Garbage Garbage Garbage Garbage Garbage


Value 65 68 47 87 89
value value value value value

 The elements of an array which has not been initialized will have a garbage values.

 In the above initialization, memory for ten elements has been created but, only 5 values have been
initialized, so the memory for the remaining five variables (10 bytes) will remain unused.

 In order to overcome the above problem we go for the second approach.

2. An array can be initialized without specifying the index.

int marks[]={65,68,47,87,89};

In the above example, index has not been specified and so memory as big as to hold five variables(i.e. 10 bytes)
only will be created.

The value will be initialized as follows

Array element marks[0] marks[1] marks[2] marks[3] marks[4]

Value 65 68 47 87 89

 By initializing the value without specifying the index is called auto arrays.

 An individual element of array can be initialized by specifying the index.

Example

int marks[4]=54;

Here the fifth element (index starts from 0) alone will be initialized and the value 89 will be replaced by 54.

Need for an Array

The need for an array would be better understood with an example.


Problem :

We have to calcuate the average age of 10 different students.

Solution Without using Array

#include<stdio.h>
void main()
{
int raja=21;
int mani=23;
int rajesh=25;
int ram=27;
int sam=29;
int paul=28;
int rani=26;
int peter=24;
int suresh=22;
int ramesh = 30;
int sum =0;
int avg;
sum = raja + mani + rajesh + ram + sam + paul + rani + peter + suresh +ramesh;
avg=(sum)/10;
printf("%d",avg);
}
Here we are using ten different variables and if we have to caclulate the average age of 1000 persons, then it
wuold be a tedious and time consiuming process.

Solution Using Array

#include<stdio.h>
void main()
{
int age[10]={21,23,25,27,29,28,26,24,22,30};
int sum=0;
int avg;
for(int i=0;i<10;i++)
{
sum=sum+age[i];
}
avg= (sum)/10;
printf("%d",avg);
}

Here we need not worry, even if we have to calculate the average age of 1,00,000 persons, because we are going
to make only minor change in the above program.i.e instead of using 10 we are going to use 1,00,000.

The program for calculating the average age of 1,00,000 persons will be like

#include<stdio.h>
void main()
{
int age[100000]={21,23,25,27,29,28,26,24,22,30};
int sum=0;
int avg;
for(int i=0;i<100000;i++)
{
sum=sum+age[i];
}
avg= (sum)/100000;
printf("%d",avg);
}

Important Points about Arrays

 The elements of an array will be stored in contagious memory location.

 Every array holds N x K bytes of memory.

Where N  number of elements in the array

K  number of bytes required by each element within the array .

float price[12];

the array price holds 12 x 4 = 48 bytes of memory.

N  12,there are 12 floating point type elements.


K  4, each floating point value requires 4 bytes of memory.

 All the elements of an array will share the same variable name but they can be distinguished form each
other by using their index.For example

int marks[5];

Here all the five elements of the mark will share the same variable name marks, but they can be
distinguished from each other by their index like marks[0], marks[3] etc..

 Any particular element of an array can be accessed or modified separately without disturbing the other
elements of the array.

 The elements of an array can be assigned to another ordinary variable or array variable of its same data
type.

Example

int a[3] = {12,45,26}


int b[4] = {11,33,22,44}
int c =15;
a[0] a[1] a[2] b[0] b[1] b[2] b[3] c

12 45 26 11 33 22 44 15

c=a[2];// value of third element in array a is assigned to c


a[0] a[1] a[2] b[0] b[1] b[2] b[3] c

12 45 26 11 33 22 44 26

a[0]=a[1];// value of second element in array a is assigned to first element in array a


a[0] a[1] a[2] b[0] b[1] b[2] b[3] C

45 45 26 11 33 22 44 15

a[1]=b[2];// value of third element in array b is assigned to second element in array a


a[0] a[1] a[2] b[0] b[1] b[2] b[3] c

12 22 26 11 33 22 44 15

But the below assignment is not possible hence an entire array cannot be assigned to a single variable.

b=a;//invalid
3.1.4 How Array is Stored

3.1.5 Reading and Writing the Elements of Array

Consider, if an array has 100 elements and if one has to read and write all the 100 elements of an array, then it
will be a tedious and time consuming process as the program will contain 100 read and write statements as
follows.

For Reading,

scanf(“%d”,&a[1]);// reading the first element


scanf(“%d”,&a[2]);// reading the second element
scanf(“%d”,&a[3]);// reading the third element
…………………
……………..
scanf(“%d”,&a[1]);// reading the Nth element
For Writing

printf(“%d”,&a[1]);// writing the first element


printf(“%d”,&a[2]);// writing the second element
printf(“%d”,&a[3]);// writing the third element
…………………
……………..
printf(“%d”,&a[1]);// writing the Nth element

When you observe the scanf()and printf() statements, only the index has been changing from the first statement
till the last statement.

So the N statements for reading and writing can be rewritten as a single statement as follows

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


{
scanf(“%d”,&a[i]);
}

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


{
printf("%d”,a[i]);
}
 N specifies the number of elements to be read or written.
 Each time when the value of i increments, the successive elements of an array is read/written.
 Till now all we have seen is about single dimensional array. In the upcoming chapter, we will see about
two and three dimensional arrays.

Example Program
/* C program to find the total marks of five different subjects of a students using arrays */

#include <stdio.h>
void main()
{
int marks[10];
int i,n;
int sum=0;
printf("Enter number of subjects: ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("Enter marks of subject%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i]; //sum=sum+marks[i]
}
printf("total marks= %d",sum);
}
Output
Enter number of subjects: 4
Enter marks of subject1: 24
Enter marks of subject2: 45
Enter marks of subject3: 65
Enter marks of subject4: 45
total marks= 179

3.1.6 Two Dimensional Array (2D)

Definition

 Two dimensional arrays can be defined as an array of single dimensional arrays.

 It’s an array of array.

 It’s represented by rows and columns

Syntax

Data_Type Array_Name[index1][index2];

or

Storage_Class Data_Type Array_Name[index1][index2];

Example 1

int temp[3][3]

temp[0][0] temp[0][1] temp[0][2]

temp[1][0] temp[1][1] temp[1][2]

temp[2][0] temp[2][1] temp[2][2]

Initilization

int temp[ ][ ]={4, 5,8,1,3,2,9,6,7}

4 5 8

1 3 2
9 6 7

Initialization

In C, two dimensional arrays can be initialized in different number of ways.

int c[2][3]={{1,3,0}, {-1,5,9}};

OR

int c[][3]={{1,3,0}, {-1,5,9}};

OR

int c[2][3]={1,3,0,-1,5,9};

Here the array c has two rows and three columns ant it will be represented as

c[0][0] c[0][1] c[0][2]

1 3 0

c[1][0] c[1][1] c[1][2]

-1 5 9

Now Consider the single dimensional array marks[5] which contains marks of
five different subjects.

marks[5] ={65,68,47,87,89};

Array marks[0] marks[1] marks[2] marks[3] marks[4]

Element

Value 65 68 47 87 89

Now assume that these five subject marks need to be stored for five different students, then another dimension
(two dimensions) would be required and the five different subject marks of five different students would be
stored in a matrix format, where columns would represent marks and rows will represent students.

The following table shows representation of two dimensional array .


marks[5][5]={{65,68,47,87,89},{84,81,82,94,93},{78,79,61,87,82},{81,56,68,
91,78},{46,48,64,66,82}};

Array Marks[0] marks[1] marks[2] marks[3] marks[4]


Element subject2 subject3 subject4
subject1 subject5

marks[0]
65 68 47 87 89
student1

marks [1]
84 81 82 94 93
student2

marks [2]
78 79 61 87 82
student3

marks [3]
81 56 68 91 78
student4

marks [4]
46 48 64 66 82
student5

For an instance, marks[2][1]=79 means that, the mark of the student3 in subject2 is 79.

Reading and Writing elements in two dimensional arrays

Let us see how to read and write elements in a two dimensional array for the above scenario.

For Reading

for (i = 0; i < 5; i++ )


{
for (j = 0; j < 5; i++ )
{
scanf(“%d”,&marks[i][j]);
}
}
 We use two for loops. The first time when the inner loop executes it reads the five subject marks of the
first student and when it executes the next time it reads the marks of the second student and so on.
 The outer for loop executes for five times i.e for each student and the inner loop executes fir 25 times i.e
for each marks

For Writing

for (i = 0; i < 5; i++ )


{
for (j = 0; j < 5; i++ )
{
printf(“%d”,marks[i][j]);
}
}
Example Program
/* C program to find the total marks five different subjects of five different students using arrays */

void main()
{
int marks[10][10];
int i,j,m,n;
int sum1=0,sum2=0;
printf("Enter number of students: ");
scanf("%d",&m);
printf("Enter number of subjects: ");
scanf("%d",&n);
for(i=0;i<m;++i)
{
printf("\nEnter details of student%d:\n",i+1);
for(j=0;j<n;++j)
{
printf(" Enter marks of subject%d: ",j+1);
scanf("%d",&marks[i][j]);
sum2+=marks[i][j];
}
printf("\ntotal marks of student%d is %d\n",i+1,sum2);
sum1+=sum2;
sum2=0;//have to reset to use for next student
}
printf("\n\n\ttotal marks of all student is %d",sum1);
}
Output
Enter number of students: 3
Enter number of subjects: 5

Enter details of student1:


Enter marks of subject1: 56
Enter marks of subject2: 76
Enter marks of subject3: 86
Enter marks of subject4: 56
Enter marks of subject5: 67

total marks of student1 is 341

Enter details of student2:


Enter marks of subject1: 66
Enter marks of subject2: 77
Enter marks of subject3: 88
Enter marks of subject4: 99
Enter marks of subject5: 66

total marks of student2 is 396

Enter details of student3:


Enter marks of subject1: 98
Enter marks of subject2: 98
Enter marks of subject3: 90
Enter marks of subject4: 97
Enter marks of subject5: 96

total marks of student3 is 479

total marks of all student is 1216


Example Program

//Matrix Addition using two dimensional array

#include <stdio.h>

#include <stdlib.h>

void main()

int a[2][2], b[2][2], c[2][2];

int i,j;

printf("Enter the elements of 1st matrix\n");

for(i=0;i<2;++i)

for(j=0;j<2;++j)

printf("Enter a[%d][%d]: ",i+1,j+1);

scanf("%d",&a[i][j]);

printf("Enter the elements of 2nd matrix\n");

for(i=0;i<2;++i)

for(j=0;j<2;++j)

{
printf("Enter b[%d][%d]: ",i+1,j+1);

scanf("%d",&b[i][j]);

for(i=0;i<2;++i)

for(j=0;j<2;++j)

c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays. */

printf("\nSum Of Matrix:\n");

for(i=0;i<2;++i)

for(j=0;j<2;++j)

printf("%d\t",c[i][j]);

printf("\n"); /* To display matrix sum in order. */

Output
Enter the elements of 1st matrix

Enter a[1][1]: 1

Enter a[1][2]: 3

Enter a[2][1]: 5

Enter a[2][2]: 7

Enter the elements of 2nd matrix

Enter b[1][1]: 2

Enter b[1][2]: 4

Enter b[2][1]: 6

Enter b[2][2]: 8

Sum Of Matrix:

3 7

11 15

3.1.7 Three Dimensional Array

Definition

Three dimensional arrays can be defined as an array of two dimensional arrays.

Declaration

Storage_Class Data_Type Array_Name[index1][index2][index3];

Example

marks[2][5][5];

In the above example.

 The inner most index3 represent marks


 The middle index2 represents students and
 The outermost index 1 represents classes.

Let us how three dimensional arrays will be represented.

marks[0]
Class1

Element marks[0] marks[1] marks[2] marks[3] marks[4]


Array subject2 subject3 subject4
subject1 subject5

marks[0]
65 68 47 87 89
student1

marks [1]
84 81 82 94 93
student2

marks [2]
78 96 61 87 82
student3

marks [3]
81 56 68 91 78
student4

marks [4]
46 48 64 66 82
student5

marks[1]

Class2

Element marks[0] marks[1] marks[2] marks[3] marks[4]


Array subject2 subject3 subject4
subject1 subject5

marks[0]
65 68 47 87 89
student1

marks [1]
84 81 82 94 93
student2

marks [2]
78 79 61 87 82
student3

marks [3]
81 56 68 91 78
student4
marks [4]
46 48 64 66 82
student5

 For an instance, marks[0][2][1]=96 means that, the mark of the student3 from class1 in subject2 is
96
 For marks[1][3][1]=79 means that, the mark of the student3 from class2 in subject2 is 79.

Reading and Writing

Here we use three for loops for reading and writing elements in a three dimensional array.

For Reading

for (i = 0; i < 5; i++ )

for (j = 0; j < 5; i++ )

for (k = 0; k < 5; k++ )

scanf(“%d”,&marks[i][j][k]);

For Writing

for (i = 0; i < 5; i++ )

for (j = 0; j < 5; i++ )

for (k = 0; k < 5; k++ )

{
printf(“%d”,marks[i][j][k]);

The outermost for loop executes for two times i.e for each class and the middle for loop executes for ten times
i.e for each student and the inner loop executes for 50 times i.e for each marks.

The printf() or scanf() statement will execute as many number of times as the inner for loop(50 times)

Example program:

#include <stdio.h>

#include <stdlib.h>

/* C program to find the total marks of five different subjects of three students belonging to two different
classes using three dimensional arrays */

void main()

int marks[10][10][10];

int i,j,k,l,m,n;

int sum1=0,sum2=0,sum3=0;

printf("Enter number of classes: ");

scanf("%d",&l);

printf("Enter number of students: ");

scanf("%d",&m);

printf("Enter number of subjects: ");


scanf("%d",&n);

for(i=0;i<l;++i)

printf("\nEnter details of class%d:\n",i+1);

for(j=0;j<m;++j)

printf("\nEnter details of student%d:\n",j+1);

for(k=0;k<n;++k)

printf(" Enter marks of subject%d: ",k+1);

scanf("%d",&marks[i][j][k]);

sum3+=marks[i][j][k];

printf("\ntotal marks of student%d is %d\n",j+1,sum3);

sum2+=sum3;

sum3=0;//have to reset to use for next student

printf("\ntotal marks of class%d is %d\n",i+1,sum2);

sum1+=sum2;

sum2=0;//have to reset to use for next class

printf("\n\n\ttotal marks of both the class is %d",sum1);

Output :

Enter number of classes: 2


Enter number of students: 3

Enter number of subjects: 5

Enter details of class1:

Enter details of student1:

Enter marks of subject1: 67

Enter marks of subject2: 87

Enter marks of subject3: 67

Enter marks of subject4: 78

Enter marks of subject5: 67

total marks of student1 is 366

Enter details of student2:

Enter marks of subject1: 56

Enter marks of subject2: 78

Enter marks of subject3: 89

Enter marks of subject4: 99

Enter marks of subject5: 99

total marks of student2 is 421

Enter details of student3:

Enter marks of subject1: 98

Enter marks of subject2: 87


Enter marks of subject3: 78

Enter marks of subject4: 89

Enter marks of subject5: 99

total marks of student3 is 451

total marks of class1 is 1238

Enter details of class2:

Enter details of student1:


Enter marks of subject1: 78

Enter marks of subject2: 78

Enter marks of subject3: 67

Enter marks of subject4: 78

Enter marks of subject5: 88

total marks of student1 is 389

Enter details of student2:

Enter marks of subject1: 99

Enter marks of subject2: 99

Enter marks of subject3: 98

Enter marks of subject4: 78

Enter marks of subject5: 98

total marks of student2 is 472


Enter details of student3:

Enter marks of subject1: 98

Enter marks of subject2: 98

Enter marks of subject3: 99

Enter marks of subject4: 97

Enter marks of subject5: 99

total marks of student3 is 491

total marks of class2 is 1352

total marks of both the class is 2590

Multidimensional Array

Arrays having more than one dimensions are called as multi dimensional arrays.two and three dimensionla array
are called as multi dimensional array.However, usually multidimensional array will have more than three
dimensions.

Syntax :

Storage_Class Data_Type Array_Name[index1][index2]...[indexN];

3.1.8 Application of Array

Array is used for different verities of applications. Below are the some of the applications of array:

Array Can be Used

 for Sorting Elements

 to Perform Matrix Operation

 in CPU Scheduling
 in Recursive Function

3.1.9 Limitations of Array

Array are very useful when we have to stores multiple data under single name with same data type.

Following are some limitations of Array in C Programming.

A. Static Data

1. Array is an Static data Structure

2. Memory is Allocated during Compile time.

3. Once Memory is allocated at Compile Time it Cannot be Changed during Run-time

B. Can hold only data belonging to same Data types

1. Elements belonging to different data types cannot be stored in array

For Example, Character and Integer values can be stored inside separate array but cannot be stored in
an single array

C. Inserting data in Array is Difficult

1. Inserting element is very difficult because before inserting element in an array we have to create empty
space by shifting other elements one position ahead.

for example if we have to insert an element in position 5, then we have to shift all the elements starting
from position 5 ,to thier next position.

A[0] A[1] A[2] A[3] A[4] A[5] A[6]

20 34 55 66 77 88

If we have to insert a value 60 here then we


have to shift the positions of A[4] and A[5] to
A[5] and A[6] respectively.

A[0] A[1] A[2] A[3] A[4] A[5] A[6]

20 34 55 66 60 77 88
2. This operation is faster if the array size is smaller, but same operation will be more and more time
consuming and non-efficient in case of array with large size.

D. Deletion Operation is difficult

1. Deletion is not easy because the elements are stored in contiguous memory location.

2. If we have to delete element from the array empty space will be created and thus we need to fill the
space by moving elements up in the array.

for example if we have to delete an element in position 5, then we have to shift all the elements starting
from position 5 ,to thier previous position.

A[0] A[1] A[2] A[3] A[4] A[5]

20 34 55 66 77 88

If we have to delete the value 66 here, then


we have to shift the positions of A[4] and
A[5] to A[3] and A[4] respectively.

A[0] A[1] A[2] A[3] A[4]

20 34 55 77 88

E. Bound Checking

1. If we specify the size of array as ‘N’ then we can access elements up to ‘N-1′ but in C if we try to access
elements after ‘N-1′ i.e Nth element or N+1th element then we does not get any error message.

2. Process of checking the extreme limit of array is called Bound Checking and C does not perform Bound
Checking.

3. If the array range exceeds then we will get garbage value as result.

F. Shortage of Memory
1. Memory can be allocated at compile time only and so, if after executing program we need more space
for storing additional information then we cannot allocate additional space at run time.

G. Wastage of Memory

1. Memory can be allocated at compile time only and so, if we are creating more space than what is
actually required at run-time , then unused space will be wasted.

3.2 String

 In C Programming we don’t have Sting data type.

 In C we have to use different approach to store the string.

 We are creating array of character to create string. Suppose if we have to store the name of the person
containing N letters then those N characters are stored as character array containng N characteres.

3.2.1 Introduction to Strings

 String in C is also called as Character Array

'W','E','L','C','O','M','E'

 String is enclosed within Double quotes

"Tamilnadu" is a example of String

 Single Character is enclosed within Single quotes

‘a’ ‘1’ ‘#’

 Each Character Occupy 1 byte of Memory

Size of "Tamilnadu" = Size of 'T' +

= Size of 'a' +

= Size of 'm' +

= Size of 'i' +

= Size of 'l' +

= Size of 'n' +

= Size of 'a' +
= Size of 'd' +

= Size of 'u';

Size of "Tamilnadu" = 9 BYTES

 Each Character is stored in consecutive memory location

Address of 'T' = 2000

Address of 'a' = 2001

Address of 'm' = 2002

Address of 'i' = 2003

Address of 'l' = 2004

Address of 'n' = 2005

Address of 'a' = 2006

Address of 'd' = 2007

Address of 'u' = 2008

 String always Terminates with NULL Character (‘/0′)

char name[10] = {'T','a','m','i','l','n','a','d','u','\0'}

 NULL Character haa an ASCII value 0

ASCII Value of '\0' = 0

 Since string is just an array , it is Possible to Access Individual Character

char name[10] = "Tamilnadu";

printf(“%c %c %c %c”, name[0], name[1],name[5],name[8]);

output:

tanu

 Any character in the keyboard placed within the double quotes will be called as string

Example

“asdf”
“1234”

“#as$12”

3.2.2 Declaring a String

A string can be declared as array of characters. Every string should end with a null character (‘\0’).

Syntax

char String_Variable_name [ SIZE ] ;

String / Character Array Variable name has the same rules as naming the varaiable name.

Examples

char city[30];

char name[20];

char message[50];

Here the string message can store upto 50 characters.

Note: A Null character is a byte containing all zeros. A null character determines the end of a string. It
means that whenever the compiler sees a null character it assumes that it has reached the end of the
string.

3.2.3 Initializing a String

Whenever we declare a String then it will contain garbage values inside it. We have to initialize String or
Character array before using it.

Process of Assigning some data to String is Called Initialization of String.

The string name can be initialized as follows

char val = ‘a’;

char name[4]=”hai”;

The memory for the above string will be allocated as follows

Array
name[0] name[1] name[2] name[3]
Element
Address 1000 1001 1002 1003
Value h a I /0

If the above table is noted we can see that the fourth character is null character, even though we intentionally
did not initialize that.

Note: The last character of an array will be initialized as zero even if we did not intentionally initialize it.

There are three ways to initialize a string.

1. char name[4]=”hai”;

2. char name[4]={‘h’,’a’,’i’};

3. char name[4]={{‘h’},{‘a’},{‘i’}};

Some things to be remembered while initializing strings

1. Consider the example below

char name[3]={‘h’,’a’,’i’};

char name[4]={ ‘h’,’a’,’i’};

In the first declaration the index value is 3 which mean that the character array can store only two characters
and a null character. Since we have initialized three character values, there will be no space for the null
character and hence the compiler cannot detect the end of a string and so when we print the string it will contain
some garbage value.

In the second declaration there is enough space to accommodate three character values and a null character and
so there will not be any problem in printing the string.

So the index value of a string should be big enough to accommodate the character values as well as the null
character.

2. Consider the example below

void main()

char name1[3]={‘a’,’b’,’c’};

char name2[4]={ ‘d’,’e’,’f’};

printf(“%s\n”,name1);
printf(“%s\n”,name2);

The string name1 does not have enough space to accommodate null character and hence null character will not
be included in the string name1 and so the compiler will not detect the end of string name1 and it prints some
garbage value at the end

Output:

abcẰ

def

3.2.4 Arithmetic Operations On Character


C Programming Allows to Manipulate on String.

Whenever the Character variable is used in the expression then it can be Converted into Integer Value called
ASCII value.

All Characters can be Manipulated with that Integer Value.(Addition, Subtraction)

Examples :

1. ASCII value of : ‘a’ is 97

2. ASCII value of : ‘z’ is 121

Manipulation

Displaying ASCII value[ Note that %d in Printf ]

char x = 'a';

printf("%d",x); // it prints 97

Displaying Character value[ Note that %c in Printf ]

char x = 'a';

printf("%c",x); // it prints ‘a’

Displaying the ASCII value of the next character in the alphabet[ Note that %d in Printf ]
char x = 'a' + 1 ;

printf("%d",x); // Display Result = 98 ( ascii of 'b' )

Displays the next Character in the alphabet[Note that %c in Printf ]

char x = 'a' + 1;

printf("%c",x); // Display Result = 'b'

Displaying Difference between 2 ASCII values [Note %d in Printf ]

char x = 'z' - 'a';

printf("%d",x);

/* Display Result = 25

(difference between ASCII of z and a ) */

Displaying the character which has an equivalent ASCII value of the Difference between 2 Characters
[Note that %c in Printf ]

char x = 'z' - 'a';

printf("%c",x);

/* Display Result = ↓

( difference between ASCII of z and a ) */

Note: ascii value of ↓ is 25.

3.2.5 String Manipulation Functions


String manipulation functions are the built in functions in C. Each function has a specific purpose There are lot
of operations that can be done with the strings and they are listed below

char string[30]="hai how are you";

char string2[30]=”hai”;

char string1[30]=”hello”;
char string3[30]=”welcome”;

Functions Descriptions Syntax /Example Result


strlen() It calculates the Syntax: It returns an
length of the given int strlen(stringName); integer
string
Example:
int length = strlen(string);
strcpy() It copies the content Syntax: -
of source string into char *strcpy (char *dest, char *src);
destination string
Example:
strcpy(string1,string2);
strncpy() It copies the content Syntax: -
(up to a specified char *strncpy(char *string1, char *string2,
length)of source int n);
string into
destination string Example:
strcpy(string1,string2,3);
strcmp() It checks whether Syntax: Returns
source string and int strcmp(char *string1, char *string2);
0 ,-1,+1.
destination string
Example: If -1 ,it
are equal.(case means
sensitive i.e the char string1[20]="abc"; string1 is less
string “abc” and char string2[10]="ABC"; than string2.
“ABC” are
considered as two int a=strcmp(string2,string1); If 0 means
different strings ) Note: (comparision are made according to string1 is
ascii value) equal to
string2,
If 1 means
string1 is
greater than
string2.
stricmp() It checks whether Syntax: Returns 0 ,-
source string and 1,+1.
int strcmp(char *string1, char *string2);
destination string
are equal.(case Example:
insensitive i.e the char string1[20]="abc";
string “abc” and
“ABC” are char string2[10]="ABC";
considered as equal int a=stricmp(string2,string1);
)
strncmp() It checks whether Syntax: Returns the
the first n characters int strncmp(char *string1, char *string2, difference
of source string and between ascii
int n);
destination string value of the
are equal.(case Example: two
sensitive) char string1[20]="Abcdgh"; characters
that are
char string2[10]="abcdgh"; mismatched.
int a=strncmp(string2,string1,4);
strnicmp() It checks whether Syntax: Returns 0 ,-
the first n characters int strnicmp(char *string1, char *string2, 1,+1.
of source string int n);
and destination
Example:
string
char string1[20]="abcdef";
are equal.(case
insensitive) char string2[10]="abcdgh";
int a=strnicmp(string2,string1,4);
strlwr() It converts the Syntax:
specified string into char *strlwr(char *s);
lowercase (small
letters) Example:
char string1[20]="ABCDE"; -
strlwr(string1);
strupr() It converts the Syntax:
specified string into char *strupr(char *s);
uppercase(CAPITA
L LETTERS) Example:
char string1[20]="abcdef"; -
strupr(string1);
strchr() It returns the Syntax: It returns the
address of the first adress of an
char *strchr(const char *s, int c);
occurrence of a character
given character in a Example:
string.(search starts char string1[20]="madam";
form the beginning)
char *p;
p=strchr(string1,'a');
strrchr() It returns the Syntax: It returns the
address of the first adress of an
char *strrchr(const char *s, int c);
occurrence of a character
given character in a Example:
string.(search starts char string1[20]="madam";
form the end in a
reverse order) char *p;
p=strrchr(string1,'a');
strstr() It searches for Syntax: It returns the
destination string char *strstr(const char *s1, const char adress of an
character
in source string and *s2);
if it is found it
Example:
returns the address
of the first character char string1[20]="i am ";
of destination string char string2[10]="fine";
. strstr(string1,string2);
strcat() it appends Syntax: -
destination string char *strcat(char *dest, const char *src);
into source string
Example:
char string1[20]="i am ";
char string2[10]="fine";
strcat(string1,string2);
strncat() It appends the first n Syntax: -
characters of char *strncat(char *dest, const char *src,
destination string size_t maxlen);
into source string
Example
char string1[20]="i am ";
char string2[10]="good and fine";
strncat(string1,string2,4);
strrev() It reverses the given Syntax: -
string char *strrev(char *s);
Example:
strrev(string1);
strset() It replaces a given Syntax: -
string with the char *strset(char *s, int ch);
specified character
Example:
strset(string1,’a’);
strnset() It replaces the first n Syntax: -
characters of the char *strnset(char *s, int ch, size_t n);
given string with
the specified Example:
character strnset(string1,'a',2);
strspn() It returns the Syntax: -
number up to which size_t strcspn(const char *s1, const char
characters the
source string and *s2);
destination string
Example:
are equal
int k;
k=strspn(string1,string2);
strpbrk() It returns the Syntax: It returns the
characters of source char *strpbrk(const char *s1, const char adress of an
string from, where character
*s2);
the characters of
destination string Example:
matches with char *ch;
source string, up to ch=chstrpbrk(string1,string2);
the end of string1

Example

strlen() Output
int main()
{ 5
char string1[20]="hello";
int k;
k=strlen(string1);
printf("%d",k);
return 0;
}
strcpy() Output
int main()
{ Hello
char string1[20]="hello";
char string2[10];
strcpy(string2,string1);
printf("%s",string2);
return 0;
}
strncpy() Output
int main()
{ He
char string1[20]="hello";
char string2[10];
strncpy(string2,string1,2);
printf("%s",string2);
return 0;
}
strcmp() Output
int main()
{ -1
char string1[20]="abc";
char string2[10]="ABC";
int a;
a=strcmp(string2,string1);
printf("%d",a);
return 0;
}
stricmp() Output
void main()
{ 0
char string1[20]="abc";
char string2[10]="ABC";
int a;
a=stricmp(string2,string1);
printf("%d",a);
return 0;
}
strncmp() Ouptut
void main()
{ 32
char string1[20]="Abcdgh";
char string2[10]="abcdgh"; Note:
int a; The difference between the ASCII value of
a(97) and A(65) are displayed
a=strncmp(string2,string1,4);
printf("%d",a);
return 0;
}
strnicmp() Output
void main()
{ 0
char string1[20]="abcdef";
char string2[10]="abcdgh"; Only the first four characters are compared
and they are equal. the remaining characters
int a;
are ignored
a=strnicmp(string2,string1,4);
printf("%d",a);
return 0;
}
strlwr() Ouptut
int main()
{ abcdef
char string1[20]="ABCDEF";
strlwr(string1);
printf("%s",string1);
return 0;
}
strupr() Ouptut
int main()
{ ABCDEF
char string1[20]="abcdef";
strupr(string1);
printf("%s",string1);
return 0;
}
strchr() Output
int main()
{ adam
char string1[20]="madam";
char *p;
p=strchr(string1,'a');
printf("%s",p);
return 0;
}
strrchr() Output
int main()
{ Am
char string1[20]="madam";
char *p;
p=strrchr(string1,'a');
printf("%s",p);
return 0;
}
strstr() Ouput
int main()
{ adam
char string1[20]="madam";
char string2[10]="ada"; Note: if the destination string is not found null
character will be returned
char *p;
p=strstr(string1,string2);
printf("%s",p);
return 0;
}
strcat() Output
int main()
{ i am fine
char string1[20]="i am ";
char string2[10]="fine";
strcat(string1,string2);
printf("%s",string1);
return 0;
}
strncat() Output
int main()
{ i am good
char string1[20]="i am ";
char string2[10]="good and fine";
strncat(string1,string2,4);
printf("%s",string1);
return 0;
}
strset() Output
int main()
{ $$$
char string1[20]="hai";
strset(string1,'$');
printf("%s",string1);
return 0;
}
strnset() Output
int main()
{ $$i
char string1[20]="hai";
strnset(string1,'$',2);
printf("%s",string1);
return 0;
}
strspn() Output
int main()
{ 5
char string1[20]="i am sam";
char string2[20]="i am ram"; Note: blank space is also counted as character.
int k;
k=strspn(string1,string2);
printf("%d",k);
return 0;
}
strpbrk() Output
int main()
{ tall and strong
char string1[30]="he is tall and strong";
char string2[30]="tall";
char *p;
p=strpbrk(string1,string2);
printf("%s",p);
return 0;
}
.

3.3 Sorting (Simple Programs)

3.4 Searching (Simple Programs)

3.5 Matrix Operations

You might also like