You are on page 1of 36

Programming for Problem Solving (3110003) Chapter – 4: Array & String

Subject
Programming for Problem Solving (3110003)

Chapter – 4
Array & String

Prepared by – Prof. Viral H. Panchal 1


Programming for Problem Solving (3110003) Chapter – 4: Array & String

CONTENTS
1. CONCEPTS OF ARRAY
2. ONE-DIMENSIONAL ARRAYS
2.1. Declaration of One-dimensional Arrays
2.2. Initialization of One-dimensional Arrays
2.3. Solved Programs (One-dimensional Arrays)
3. TWO-DIMENSIONAL ARRAYS
3.1. Declaration of Two-dimensional Arrays
3.2. Initialization of Two-dimensional Arrays
3.3. Solved Programs (Two-dimensional Arrays)
4. MULTIDIMENSIONAL ARRAYS
5. STRINGS
5.1. Reading Strings
5.2. Printing Strings
6. BUILT-IN STRING FUNCTIONS (STRING-HANDLING FUNCTIONS)
6.1. strcat() Function
6.2. strcmp() Function
6.3. strcpy() Function
6.4. strlen() Function
6.5. strrev() Function
6.6. Other String Functions
7. SOLVED PROGRAMS (STRINGS)

Prepared by – Prof. Viral H. Panchal 2


Programming for Problem Solving (3110003) Chapter – 4: Array & String

1. CONCEPTS OF ARRAY
• An array is a collection of elements of similar data types referred by the same
variable name.
• An array is a linear and homogeneous data structure. Linear data structure stores
its individual data elements in a sequential order in the memory. Homogeneous
means all individual data elements are of the same data type.
• The individual elements of an array are referred by their index or sub-script
value. In C the index begins at zero and is always written inside square brackets.
• For example, if marks of 10 students are stored in an array named mark, then
mark[0] refers to the marks of the first student, mark[1] refers to the marks of the
second student and mark[9] refers to the marks of the tenth student, that is,
mark[n-1] refers to the marks of nth student.

Advantages of Array:
o Unlike variable an array can store number of values under single name.
o The array elements are stored contiguously.
o Array index helps to access any random values from the array and perform
operations on it.
o An array is a flexible data structure, means we can perform addition or
removal of elements at any position.

Disadvantages of Array:
o Only elements of same data types can be stored in an array. We cannot
store elements of multiple data types in a single array.
o If array size is big, that much amount of memory gets reserved.
o Big size of arrays and multi-dimensional arrays are complicated to access
and manipulate.
o If there is need to store more elements than array size, then it is not possible
and shortage of memory occurs.
o If less elements are stored than array size then it leads to memory wastage.

Types of Arrays:
o Arrays are categorized according to the dimensions used to define it. Here
the dimension indicates the number of rows and columns used to set size of an
array.
o There are following types of arrays:
1. One-dimensional arrays
2. Two-dimensional arrays
3. Multidimensional arrays

Prepared by – Prof. Viral H. Panchal 3


Programming for Problem Solving (3110003) Chapter – 4: Array & String

2. ONE-DIMENSIONAL ARRAYS
• An array with single subscript is called as one-dimensional array.

2.1. Declaration of One-dimensional Arrays


• The syntax of declaring one-dimensional array is:
data_type array_name[size];

where,
data_type = the type of data stored in the array
array_name = name of the array
size = maximum number of elements that an array can hold

• For example,
float height[20];

declares the height to be an array containing 20 real elements. Any subscripts 0


to 19 are valid.
• Similarly,

int marks[10];

declares the marks as an array to contain a maximum of 10 integer constants.


• The C language treats character strings simply as arrays of characters. The size
in a character string represents the maximum number of characters that the string
can hold.
• For example,

char name[10];

declares the name as a character array (string) variable that can hold a
maximum number of 10 characters.
• Suppose we read the following string constant into the string variable name.
“WELL DONE”
• Each character of the string is treated as an element of an array name and is
stored in the memory as follows:
‘W’ ‘E’ ‘L’ ‘L’ ‘’ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’
• When the compiler sees a character string, it terminates it with an additional null
character. Thus, the element name[10] holds the null character ‘\0’.
• When declaring character arrays, we must allow an extra element space for the
null terminator.

Prepared by – Prof. Viral H. Panchal 4


Programming for Problem Solving (3110003) Chapter – 4: Array & String

2.2. Initialization of One-dimensional Arrays


• After an array is declared, its elements must be initialized. Otherwise, they will
contain “garbage”.
• You can initialize the array elements one by one.
Syntax:
array_name[index] = value;

For example,
marks[0] = 35;
marks[1] = 70;
.
.
.
marks[9] = 86;
• You can also initialize the complete array directly.
Syntax:
data_type array_name[size] = {list of values};

For example,
int marks[10] = {35,70,40,55,26,43,56,82,78,86};

This array is stored in the memory as follows:

35 70 40 55 26 43 56 82 78 86
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]

• The declaration and initialization of character array:


Example:
char a[8] = {‘L’,’E’’A’,’R’,’N’,’ ‘,’C’};

This array is stored in the memory as follows:


‘L’ ‘E’ ‘A’ ‘R’ ‘N’ ‘’ ‘C’ ‘\0’
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7]
• The declaration and initialization of float array:
Example:
float price[4] = {1.25,0.75,3.5,10.2};

This array is stored in the memory as follows:


1.25 0.75 3.5 10.2
price[0] price[1] price[2] price[3]

Prepared by – Prof. Viral H. Panchal 5


Programming for Problem Solving (3110003) Chapter – 4: Array & String

• The array size may be omitted during declaration.


Example:
int marks[] = {45,66,84};

is equivalent to
int marks[3] = {45,66,84};

In such cases, the subscript is assumed to equal to the number of elements in the
array (3 in this case).

• The elements which are not explicitly initialized are automatically set to zero.
Example:
int x[5] = {2,5};

implies
x[0] = 2;

x[1] = 5;

x[2] = 0;

x[3] = 0;

x[4] = 0;

Prepared by – Prof. Viral H. Panchal 6


Programming for Problem Solving (3110003) Chapter – 4: Array & String

2.3. Solved Programs (One-dimensional Arrays)


/* Write a program to get n numbers and find sum and average of
numbers */

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n;
float avg,sum=0;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
sum=sum+a[i];
}
avg=sum/n;
printf("\nArray elements are: ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nSum = %0.2f \nAverage = %0.2f",sum,avg);
getch();
}

Output:
Enter value of n (not more than 10): 5
Enter number 1: 12
Enter number 2: 23
Enter number 3: 8
Enter number 4: 56
Enter number 5: 9

Array elements are: 12 23 8 56 9


Sum = 108.00
Average = 21.60

Prepared by – Prof. Viral H. Panchal 7


Programming for Problem Solving (3110003) Chapter – 4: Array & String

/* Write a program find largest and smallest number from given n


numbers */

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,max,min;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
}
max=a[0];
min=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf("\nArray elements are: ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nLargest = %d \nSmallest = %d",max,min);
getch();
}

Output:
Enter value of n (not more than 10): 5
Enter number 1: 7
Enter number 2: 2
Enter number 3: 9
Enter number 4: 5
Enter number 5: 6

Array elements are: 7 2 9 5 6


Largest = 9
Smallest = 2

Prepared by – Prof. Viral H. Panchal 8


Programming for Problem Solving (3110003) Chapter – 4: Array & String

/* Write a program to find number of odd and even numbers from


given n numbers */

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,odd=0,even=0;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
if(a[i]%2==0)
even++;
else
odd++;
}
printf("\nArray elements are: ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nNumber of Odd = %d \nNumber of Even =
%d",odd,even);
getch();
}

Output:
Enter value of n (not more than 10): 7
Enter number 1: 4
Enter number 2: 3
Enter number 3: 1
Enter number 4: 7
Enter number 5: 6
Enter number 6: 8
Enter number 7: 9

Array elements are: 4 3 1 7 6 8 9


Number of Odd = 4
Number of Even = 3

Prepared by – Prof. Viral H. Panchal 9


Programming for Problem Solving (3110003) Chapter – 4: Array & String

/* Write a program which finds maximum of n numbers and also


finds how many times maximum number is repeated */

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,max,count;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
max=a[0];
}
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
count=0;
for(i=0;i<n;i++)
{
if(max==a[i])
count++;
}
printf("\nArray elements are: ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nMaximum number = %d and is repeated %d
times",max,count);
getch();
}

Output:
Enter value of n (not more than 10): 8
Enter number 1: 12
Enter number 2: 34
Enter number 3: 23
Enter number 4: 34
Enter number 5: 32

Prepared by – Prof. Viral H. Panchal 10


Programming for Problem Solving (3110003) Chapter – 4: Array & String

Enter number 6: 4
Enter number 7: 34
Enter number 8: 24

Array elements are: 12 34 23 34 32 4 34 24


Maximum number = 34 and is repeated 3 times

/* Write a program to sort given n numbers and display them in


ascending and descending order */

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,n,temp;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\nNumbers in ascending order:\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nNumbers in descending order:\n");
for(i=n-1;i>=0;i--)
printf("%4d",a[i]);
getch();
}

Prepared by – Prof. Viral H. Panchal 11


Programming for Problem Solving (3110003) Chapter – 4: Array & String

Output:
Enter value of n (not more than 10): 7
Enter number 1: 8
Enter number 2: -2
Enter number 3: 12
Enter number 4: 23
Enter number 5: -6
Enter number 6: 45
Enter number 7: 9

Numbers in ascending order:


-6 -2 8 9 12 23 45
Numbers in descending order:
45 23 12 9 8 -2 -6

3. TWO-DIMENSIONAL ARRAYS
• An array with two subscripts is called as two-dimensional array.
• 2D arrays are mostly used to perform matrix operations.
• A matrix has two subscripts – the first subscript denotes the number of rows and
the second subscript denotes the number of columns.

3.1. Declaration of Two-dimensional Arrays


• The syntax of declaring two-dimensional array is:
data_type array_name[row_size][column_size];

where,
data_type = the type of data stored in the array
array_name = name of the array
row_size = maximum number of rows in the array
column_size = maximum number of columns in the array

• For example,
int table[2][3]; //implies 2 rows and 3 columns

declares the table to be an array containing 2 rows and 3 columns, i.e., total 6
real elements.
• A user can view this array as below.
Column 0 Column 1 Column 2
Row 0 [0][0] [0][1] [0][2]
Row 1 [1][0] [1][1] [1][2]

Prepared by – Prof. Viral H. Panchal 12


Programming for Problem Solving (3110003) Chapter – 4: Array & String

• But in memory it will form different structure as below.

table[0][0] 4000
table[0][1] 4002
table[0][2] 4004 Memory
table[1][0] 4006 Address

table[1][1] 4008
table[1][2] 4010

3.2. Initialization of Two-dimensional Arrays


• The two-dimensional array can be initialized at the time of declaration as in the
case of single dimensional array.
• For example,

int table[2][3] = {0,0,0,1,1,1};

initialize first row data as {0,0,0} and second row data as {1,1,1}.
• The above initialization is same as

int table[2][3] = {{0,0,0},{1,1,1}};

• If the values are missing in an initializer, they are automatically set to 0. For
example, the statement
int table[2][3] = {{1,1},{2}};

will initialize the first two elements of the first row to 1, the first element of the
second row to 2, and all other elements to 0.

Prepared by – Prof. Viral H. Panchal 13


Programming for Problem Solving (3110003) Chapter – 4: Array & String

3.3. Solved Programs (Two-dimensional Arrays)


/* Write a program to find maximum number within 3x3 matrix */

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j,max;
clrscr();
printf("Enter the elements of matrix A:\n");
for(i=0;i<3;i++) //Get matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0;i<3;i++) //Display matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
max=a[0][0];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(a[i][j]>max)
max=a[i][j];
}
}
printf("\nThe Largest number in the matrix A is: %d",max);
getch();
}

Prepared by – Prof. Viral H. Panchal 14


Programming for Problem Solving (3110003) Chapter – 4: Array & String

Output:
Enter the elements of matrix A:
a[0][0] = 5
a[0][1] = 23
a[0][2] = 7

a[1][0] = 85
a[1][1] = 61
a[1][2] = 3

a[2][0] = 67
a[2][1] = 99
a[2][2] = 2

Matrix A:
5 23 7
85 61 3
67 99 2

The Largest number in the matrix A is: 99

/* Write a program to find addition two 3x3 matrices */

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("Enter the elements of first matrix:\n");
for(i=0;i<3;i++) //Get first matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("Enter the elements of second matrix:\n");
for(i=0;i<3;i++) //Get second matrix data
{
for(j=0;j<3;j++)

Prepared by – Prof. Viral H. Panchal 15


Programming for Problem Solving (3110003) Chapter – 4: Array & String

{
printf("a[%d][%d] = ",i,j);
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0;i<3;i++) //Display first matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nMatrix B:\n");
for(i=0;i<3;i++) //Display second matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",b[i][j]);
}
printf("\n");
}
printf("\nAddition of matrix A and B:\n");
for(i=0;i<3;i++) //calculate sum and display result matrix
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%4d",c[i][j]);
}
printf("\n");
}
getch();
}

Prepared by – Prof. Viral H. Panchal 16


Programming for Problem Solving (3110003) Chapter – 4: Array & String

Output:
Enter the elements of first matrix:
a[0][0] = 1
a[0][1] = 2
a[0][2] = 3

a[1][0] = 4
a[1][1] = 5
a[1][2] = 6

a[2][0] = 7
a[2][1] = 8
a[2][2] = 9

Enter the elements of second matrix:


a[0][0] = 9
a[0][1] = 8
a[0][2] = 7

a[1][0] = 6
a[1][1] = 5
a[1][2] = 4

a[2][0] = 3
a[2][1] = 2
a[2][2] = 1

Matrix A:
1 2 3
4 5 6
7 8 9

Matrix B:
9 8 7
6 5 4
3 2 1

Addition of matrix A and B:


10 10 10
10 10 10
10 10 10

Prepared by – Prof. Viral H. Panchal 17


Programming for Problem Solving (3110003) Chapter – 4: Array & String

/* Write a program to find transpose of any 3x3 matrix */

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
clrscr();
printf("Enter the elements of matrix:\n");
for(i=0;i<3;i++) //Get matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0;i<3;i++) //Display matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nTranspose of A:\n");
for(j=0;j<3;j++) //Display transpose of matrix
{
for(i=0;i<3;i++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
getch();
}

Prepared by – Prof. Viral H. Panchal 18


Programming for Problem Solving (3110003) Chapter – 4: Array & String

Output:
Enter the elements of matrix:
a[0][0] = 1
a[0][1] = 2
a[0][2] = 3

a[1][0] = 4
a[1][1] = 5
a[1][2] = 6

a[2][0] = 7
a[2][1] = 8
a[2][2] = 9

Matrix A:
1 2 3
4 5 6
7 8 9

Transpose of A:
1 4 7
2 5 8
3 6 9

Prepared by – Prof. Viral H. Panchal 19


Programming for Problem Solving (3110003) Chapter – 4: Array & String

/* Write a program to find multiplication two 3x3 matrices */

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k,sum;
clrscr();
printf("Enter the elements of first matrix:\n");
for(i=0;i<3;i++) //Get first matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("Enter the elements of second matrix:\n");
for(i=0;i<3;i++) //Get second matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0;i<3;i++) //Display first matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nMatrix B:\n");
for(i=0;i<3;i++) //Display second matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",b[i][j]);
}

Prepared by – Prof. Viral H. Panchal 20


Programming for Problem Solving (3110003) Chapter – 4: Array & String

printf("\n");
}
for(i=0;i<3;i++) //Finding multiplication of two matrices
{
for(j=0;j<3;j++)
{
sum=0;
for(k=0;k<3;k++)
sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
}
}
printf("\nMultiplication of matrix A and B:\n");
for(i=0;i<3;i++) //display result matrix
{
for(j=0;j<3;j++)
{
printf("%4d",c[i][j]);
}
printf("\n");
}
getch();
}

Output:
Enter the elements of first matrix:
a[0][0] = 1
a[0][1] = 2
a[0][2] = 3

a[1][0] = 4
a[1][1] = 5
a[1][2] = 6

a[2][0] = 7
a[2][1] = 8
a[2][2] = 9

Enter the elements of second matrix:


a[0][0] = 1
a[0][1] = 1
a[0][2] = 1

Prepared by – Prof. Viral H. Panchal 21


Programming for Problem Solving (3110003) Chapter – 4: Array & String

a[1][0] = 2
a[1][1] = 2
a[1][2] = 2

a[2][0] = 3
a[2][1] = 3
a[2][2] = 3

Matrix A:
1 2 3
4 5 6
7 8 9

Matrix B:
1 1 1
2 2 2
3 3 3

Multiplication of matrix A and B:


14 14 14
32 32 32
50 50 50

4. MULTIDIMENSIONAL ARRAYS
• An array with more than two subscripts is called as multidimensional array.
• For example, suppose we want to store 5 students marks information for 2
different exams carried out in the term for 4 different subjects, this data can be
stored by using 3-dimensional array like,
int marks[5][2][4];

where, 5 students, 2 exams, and 4 subjects. So, total entries in the array will be
5*2*4 = 40.
• The array will span from marks[0][0][0] to marks[4][1][3].

Prepared by – Prof. Viral H. Panchal 22


Programming for Problem Solving (3110003) Chapter – 4: Array & String

5. STRINGS
• A string is a sequence of characters enclosed in double quotes.
• In C, each string is terminated by a special character called null character and it
is represented as ‘\0’ or NULL.
• Because of this reason, the character array must be declared one size larger
than the string required to be stored.
C O M P U T E R \0
• Here, the string stored is “COMPUTER”, which is having only 8 characters, but
actually 9 characters are stored because of NULL character at the end.
char name[20];

• This line declares an array name of characters of size 20. We can store any
string up to maximum length 19.
• String is basically an array of characters, so we can initialize the string by using
the method of initializing the single dimensional array as shown below.
char name[] = {‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’,’\0’};

OR
char name[] = “COMPUTER”;

• When the string is written is double quotes, the NULL character is not required, it
is automatically taken.

5.1. Reading Strings


• The scanf() function with format specifier %s is used to read a string in the
character array.
• For example,

char name[20];
...
...
scanf(“%s”,name);

will read the string in the array name.


• There is no need to put & symbol before the name, because the name itself is the
address of the string name.
• We can also use the gets() function for reading a string. The array name should
be written within brackets.
• For example,

Prepared by – Prof. Viral H. Panchal 23


Programming for Problem Solving (3110003) Chapter – 4: Array & String

char name[20];
...
...
gets(name);

• The advantage of gets() is that we can read strings involving blanks and tabs.
While the scanf() reads only up to blank or tab character.
• So, scanf() is used to read word while gets() can be used to read sentence
involving many words.

5.2. Printing Strings


• The string can be printed using printf() function with %s format specifier, or by
using puts() function as shown below.
char name[] = “Viral”;
...
...
printf(“%s”,name);
...
...
puts(name);

• puts() can print only one string at a time, while one printf() can print multiple
strings by using %s many times in the printf().
• For example,

char name[] = “Viral”;


char surname[] = “Panchal”;
...
printf(“%s %s”,name,surname);
...
puts(name);
puts(surname);

• Here, one statement,


printf(“%s %s”,name,surname);

prints two strings, while two statements as shown below


puts(name);
puts(surname);

are required to print name and surname using puts().

Prepared by – Prof. Viral H. Panchal 24


Programming for Problem Solving (3110003) Chapter – 4: Array & String

6. BUILT-IN STRING FUNCTIONS (STRING-HANDLING


FUNCTIONS)
• The C library supports a large number of string-handling functions that can be
used for string manipulation. Following are the most commonly used string-
handling functions.
o strcat() – concatenates two strings
o strcmp() – compares two strings
o strcpy() – copies one string over another
o strlen() – finds the length of a string
o strrev() – reverses the string

6.1. strcat() Function


• The strcat() function joins two strings together. The process of joining two strings
together is called concatenation.
• It takes two arguments, the first one is a string variable and the second can be a
string variable or a string constant.
• The characters of the second string are appended at the end of the first one.
• Syntax:

strcat(string1,string2);

• Here, string1 and string2 are character arrays (string2 can be string constant
also).
• The NULL character is removed from the end of string1 and string2 is stored from
this position.

/* Program to use strcat() function */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string1[50],string2[50];
clrscr();
printf("\nEnter the first string:\n");
gets(string1);
printf("\nEnter the second string:\n");
gets(string2);
strcat(string1,string2);

Prepared by – Prof. Viral H. Panchal 25


Programming for Problem Solving (3110003) Chapter – 4: Array & String

printf("\nUsing strcat function the resultant string


is:\n%s",string1);
getch();
}

Output:
Enter the first string:
Programming in C

Enter the second string:


is a fun

Using strcat() function the resultant string is:


Programming in C is a fun

6.2. strcmp() Function


• In C, the comparison of two strings is not allowed directly.
• The comparison can be done either using the standard library function strcmp() or
the strings can be compared character by character.
• Syntax:

strcmp(string1,string2);

• Here, string1 and string2 are string variables or string constants.


• It returns a 0 when strings are identical and returns the numeric difference
between the ASCII values of the first mismatch characters otherwise.

/* Program to use strcmp() function */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string1[50],string2[50];
int diff;
clrscr();
printf("\nEnter the first string:\n");
gets(string1);
printf("\nEnter the second string:\n");
gets(string2);
diff=strcmp(string1,string2);
if(diff==0)

Prepared by – Prof. Viral H. Panchal 26


Programming for Problem Solving (3110003) Chapter – 4: Array & String

printf("\nBoth strings are same");


else
printf("\nBoth strings are different");
getch();
}

Output 1:
Enter the first string:
Programming

Enter the second string:


Programming

Both strings are same

Output 2:
Enter the first string:
Programming

Enter the second string:


Coding

Both strings are different

6.3. strcpy() Function


• The process of copyig one string into the other is called string copying.
• In C, the function for copying of one string over the other is strcpy().
• Syntax:
strcpy(string1,string2);

• Here, string1 is the target string which stores the contents of the source string
string2.
• The string2 may be a character array variable or a string constant.
• The string1 must have a size greater than or equal to that of string2.
• The string2 is copied into the string1 character by character and the process
terminates on getting NULL character (‘\0’). in the source string.
• Note that the contents of the target string will be lost and source string remains
unchanged.

Prepared by – Prof. Viral H. Panchal 27


Programming for Problem Solving (3110003) Chapter – 4: Array & String

/* Program to use strcpy() function */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string1[50],string2[50];
clrscr();
printf("\nEnter a string:\n");
gets(string1);
strcpy(string2,string1);
printf("\nCopied string is:\n%s",string2);
getch();
}

Output:
Enter a string:
Viral Panchal

Copied string is:


Viral Panchal

6.4. strlen() Function


• The process of knowing the number of characters in a string is called finding
length of a string.
• In C, the function for finding the length of a string is strlen().
• This function finds and returns the number of characters in a string.
• Syntax:

n=strlen(string);

• Here, n is an integer variable which stores the values of the length of the string.
• The string can be both a string variable or a string constant.
• The process of counting is terminated on first occurrence of NULL character (‘\0’).

/* Program to find the length of a given string using strlen()


function */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()

Prepared by – Prof. Viral H. Panchal 28


Programming for Problem Solving (3110003) Chapter – 4: Array & String

{
char string1[50];
int n;
clrscr();
printf("\nEnter a string:\n");
gets(string1);
n=strlen(string1);
printf("\nThe length of string is %d",n);
getch();
}

Output:
Enter a string:
Viral Panchal

The length of string is 13

6.5. strrev() Function


• The strrev() function is used o print a string in reverse order.
• Syntax:
strrev(string);

• Here, the original string is overwritten with its reversed string.

/* Program to print a given string in reverse order using


strrev() function */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string1[50];
clrscr();
printf("\nEnter a string:\n");
gets(string1);
strrev(string1);
printf("\nReversed string is:\n%s",string1);
getch();
}

Prepared by – Prof. Viral H. Panchal 29


Programming for Problem Solving (3110003) Chapter – 4: Array & String

Output:
Enter a string:
Viral

Reversed String is:


lariV

6.6. Other String Functions


• The header file <string.h> contains many more string manipulation functions. That
might be useful in certain situations.

strncpy()

• In addition to the function strcpy() that copies one string to another, we have
another function strncpy() that copies only the left-most n characters of the source
string to the target string variable.
• This is a three-parameter function and is invoked as follows:

strncpy(s1,s2,n);

• This statement copies the first 5 characters of the source string s2 into the target
string s1.

strncmp()

• A variation of the function strcmp() is the function strncmp(). This function has three
parameters as illustrated in the function call below:
strncmp(s1,s2,n);

this compared the lest-most n characters of s1 to s2 and returns.


a) 0 if they are equal;
b) negative numbers, if s1 substring is less than s2; and
c) positive number, otherwise

strncat()

• This is another concatenation function that takes three parameters as shown


below:
strncat(s11,s2,n);

• This call will concatenate the left-most n characters of s2 to the end of s1.
Prepared by – Prof. Viral H. Panchal 30
Programming for Problem Solving (3110003) Chapter – 4: Array & String

strstr()

• It is a two-parameter function that can be used to locate a sub-string in a string.


• This takes the forms:
strstr(s1,s2);
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() and strrchr()

• We also have functions to determine the existence of a character in a string.


• The function call
strchr(s1,’m’);

will locate the first occurrence of the character ‘m’ and the call
strrchr(s1,’m’);

will locate the last occurrence of the character ‘m’ in the string s1.

strupr()

• This function is used to convert the characters in string to upper case.


• Syntax:
strupr(string);

strlwr()

• This function is used to convert the characters in string to lower case.


• Syntax:
strlwr(string);

Prepared by – Prof. Viral H. Panchal 31


Programming for Problem Solving (3110003) Chapter – 4: Array & String

7. SOLVED PROGRAMS (STRINGS)


/* Write a program to find a character from given string */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string[50];
char ch='o';
clrscr();
printf("\nEnter a string:\n");
gets(string);
if(strchr(string,ch))
printf("The character %c is at position: %d\n",
ch,strchr(string,ch)-string+1);
else
printf("\nThe character is not found");
getch();
}

Output 1:
Enter a string:
program

The character o is at position: 3

Output 2:
Enter a string:
viral

The character is not found

Prepared by – Prof. Viral H. Panchal 32


Programming for Problem Solving (3110003) Chapter – 4: Array & String

/* Write a program to replace a character in given string */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string[50],chr,repl_chr;
int i=0;
clrscr();
printf("\nEnter a string: ");
gets(string);
printf("\nEnter a character to be replaced: ");
scanf("%s",&chr);
printf("\nEnter replacement character: ");
scanf("%s",&repl_chr);
while(string[i]!='\0')
{
if(string[i]==chr)
{
string[i]=repl_chr;
}
i++;
}
printf("\nModified string after replacement is: %s",
string);
getch();
}

Output:
Enter a string: abcadefa

Enter a character to be replaced: a

Enter replacement character: z

Modified string after replacement is: zbczdefz

Prepared by – Prof. Viral H. Panchal 33


Programming for Problem Solving (3110003) Chapter – 4: Array & String

/* Write a program to delete a character in given string */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[50],ch;
int i,j;
clrscr();
printf("\nEnter a string: ");
gets(str);
printf("\nEnter a character to delete from string: ");
scanf("%c",&ch);
//Accessing each element of string to perform delete
operation
for(i=0;i<strlen(str);i++)
{
if(ch==str[i])
{
//After deleting user provided element moving each
element one step forward to fill it's place
for(j=i;j<strlen(str);j++)
str[j]=str[j+1];
}
}
printf("\nString after deleting character: %s",str);
getch();
}

Output:
Enter a string: Viral Panchal

Enter a character to delete from string: a

String after deleting character: Virl Pnchl

Prepared by – Prof. Viral H. Panchal 34


Programming for Problem Solving (3110003) Chapter – 4: Array & String

/* Write a program to convert string into upper case */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[50];
clrscr();
printf("\nEnter a string: ");
gets(str);
printf("\nThe string in upper case: %s",strupr(str));
getch();
}

Output:
Enter a string: viral panchal

The string in upper case: VIRAL PANCHAL

/* Write a program to read a string and determine it is


palindrome or not */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[50],str2[50];
int diff;
clrscr();
printf("\nEnter a string: ");
gets(str1);
strcpy(str2,str1);
strrev(str2);
diff=strcmp(str1,str2);
if(diff==0)
printf("\nString is a palindrome");
else
printf("\nString is not a palindrome");
getch();
}

Prepared by – Prof. Viral H. Panchal 35


Programming for Problem Solving (3110003) Chapter – 4: Array & String

Output 1:
Enter a string: malayalam

String is a palindrome

Output 2:
Enter a string: viral

String is not a palindrome

Prepared by – Prof. Viral H. Panchal 36

You might also like