0% found this document useful (0 votes)
1 views40 pages

Unit-2 Notes - PS

Module 2 of Programming in C covers arrays and strings, focusing on the declaration, initialization, and operations of one-dimensional and two-dimensional arrays. It explains array characteristics, advantages, and disadvantages, along with sample programs demonstrating array manipulation, including sorting and searching algorithms like selection sort, linear search, and binary search. The module also includes examples of how to read, print, and manipulate array elements effectively.

Uploaded by

Rahul Kn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views40 pages

Unit-2 Notes - PS

Module 2 of Programming in C covers arrays and strings, focusing on the declaration, initialization, and operations of one-dimensional and two-dimensional arrays. It explains array characteristics, advantages, and disadvantages, along with sample programs demonstrating array manipulation, including sorting and searching algorithms like selection sort, linear search, and binary search. The module also includes examples of how to read, print, and manipulate array elements effectively.

Uploaded by

Rahul Kn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Programming In C Module 2

MODULE-2
Arrays and Strings
Introduction to Arrays: Declaration, Initialization One dimensional array Two dimensional arrays -
String operations: length, compare, concatenate, copy Selection sort, linear and binary search.

Introduction to Arrays: Declaration, Initialization


Arrays a kind of data structure that can store a fixed-size sequential collection of elements of
the same type. An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type.
 Array is a collection of elements of same data type stored under common name.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an
index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Characteristics of an Array
 The elements of the array are stored in consecutive memory location and
arereferenced by an index (subscript).
 Individual elements of an array can be accesed with the integer value known as index.
 Array index starts from 0. Memory space of an array can be calculated Size of
datatype
* number of elements of an array
 An array is a data structure that is used for storage of homogeneous data.
 Arrays are used in the situation where we are asked read and prints the marks of 30
students .It is inefficient way of declaring 30 variables to hold marks. So the
concept of Array is used where one common variable is used for assigning 30
values
 A variable that can store multiple values is an array variable.
 It is a derived data type which stores related information together.
 It is classified into three types
i) One dimensional Array
ii) Two dimensional Array
iii) Multi-dimensional Array
Advantage of an array
i) It is used to represent multiple data items of same type by using only single name.
ii) 2D arrays are used to represent matrices.
iii) It allows random accessing of elements i.e. any element of the array can be randomly
accessed using indexes
Disadvantage of an array
1 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
i) Insertion and deletion of elements in an array is difficult
ii) Size of the array should be known in advance
iii) Elements in the array must be same data type

Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the number of
elements requiredby an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant
greater than zero and type can be any valid C data type. For example, to declare a 10-element
array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays

You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write –

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};


You will create exactly the same array as you did in the previous example. Following is an
example to assign a single element of the array −
balance[4] = 50.0;

The above statement assigns the 5th element in the array with a value of 50.0. All arrays have
0 as the index of their first element which is also called the base index and the last index of an
array will be total size of the array minus 1. Shown below is the pictorial representation of the
array we discussed above −

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the
2 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
element within square brackets after the name of the array. For example −
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to salary
variable.

One dimensional array

One dimensional array consists of fixed number of elements of same data


type organized as a simple linear sequence. Elements of an array can be accessed by
using a single subscript.

Declaration of one dimensional array: To declare and define an array we must


specify its name, type and size.

datatype arrayname[size];

datatype: kind of values it can store Example int, float, char, double.
arrayname:To identify the an Array
Size:maximum number of values that an array
can hold. Ex: int a[4];

Initialization of one dimensional array


i) Compile time initialization: Array initialization at the time of declaration
datatype arrayname[size]={list of values separated by comma};

Ex: int a[4]={20,45,67,89};


3 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
2000 2002 2004 2006
20 45 67 89

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

Sample
program1:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
printf(“%d \t%d\t%d\t%d”,a[0],a[1],a[2],a[3]);
getch();
}

Output:
20 45 67 89

Sample program2: The efficient way of accessing array elements is using loop

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
int i;
for(i=0;i<4;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
Output:
20 45 67 89

4 by Pooja Shrivastav, Department of MCA


Programming In C Module 2

Note:
By default the elements of an array are not initialized. They may contain some garbage
value, so before using array we must initialize the array or read some meaningful data into it.

Run time initialization: Array initialization at Run time


int a[4];
for(i=0;i<4;i++)
{
scanf(“%d”,&a[i]);
}

Sample program 3

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4],i;
printf(“Enter the elements\n”);
for(i=0;i<4;i++)
{
scanf(“%d\t”,&a[i]);
}
for(i=0;i<4;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
Output:
20 45 67 89

5 by Pooja Shrivastav, Department of MCA


Programming In C Module 2

ARRAY PROGRAMS
1. Program to read the numbers and print the given numbers in reverse order

#includ
e<stdio.
h>
#includ
e<conio
.h> void
main()
{
int a[10],i;
clrscr();
printf("Enter the
elements");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("The elements
are"); for(i=4;i>=0;i-
-)
{
printf("%d\t",a[i]);
}
getch();
}

Output:

Enter the elements:


1 2 3 4 5
The elements are
5 4 3 2 1

2. C Program To Find The Sum And Average Of Elements Of An Array


#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],sum=0,avg;
int i,j;
clrscr();
6
Programming In C Module 2

printf("Enter Elements");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<5;i++)
{

sum=sum+a[i];
}

printf("\nThe Sum of elements in an array is


%d",sum); avg=sum/5;
printf("\nThe Avg of elements in an array is%d",avg);

}
}

Output:

Enter
Elements 2
3
4
5
6
The Sum of elements in an
array is 20 The Avg of
elements in an array is 4

1. // largest in an array
#include <stdio.h>

int main() {
int a[10],i, max,n;
printf("enter the count of numbers");
scanf("%d", &n);
printf("enter list of numbers");
for (i=0;i<5;i++)
scanf("%d",&a[i]);
max=a[0];
for(i=1;i<5;i++)
if (max<a[i])
max=a[i];
printf("Largest = %d",max);
return 0;
7
Programming In C Module 2

2. //Second Largest
#include <stdio.h>

int main() {
int array[10] = {101, 11, 3, 4, 50, 69, 7, 8, 9, 0};
int loop, largest, second;

if(array[0] > array[1]) {


largest = array[0];
second = array[1];
} else {
largest = array[1];
second = array[0];
}

for(loop = 2; loop < 10; loop++) {


if( largest < array[loop] ) {
second = largest;
largest = array[loop];
} else if( second < array[loop] ) {
second = array[loop];
}
}

printf("Largest - %d \nSecond - %d \n", largest, second);

return 0;
}

3. Linear Search
#include <stdio.h>

int main() {
int a[10],i, key, flag=0;
printf("enter list of numbers");
for (i=0;i<5;i++)
scanf("%d",&a[i]);
printf("enter search element");
scanf("%d",&key);
for(i=0;i<5;i++)
{if (key==a[i])
{printf("%d found at %d", key,i+1);
flag=1;
}
8
Programming In C Module 2

}
if (flag==0)
printf("Not found");
return 0;
}

4. Implement Binary Search on


Integers
Binary Search Algorithm
Below is the step-by-step algorithm for Binary Search:

a. Divide the search space into two halves by finding the middle index “mid”.
b. Compare the middle element of the search space with the key.
c. If the key is found at middle element, the process is terminated.
d. If the key is not found at middle element, choose which half will be used as the
next search space.
e. If the key is smaller than the middle element, then the left side is used for next
search.
f. If the key is larger than the middle element, then the right side is used for next search.
g. This process is continued until the key is found or the total search space is exhausted.

Note: This algorithm works on a sorted list of numbers in ascending order

Program:
#include <stdio.h>
int main() {
int n, key, low, high, mid, arr[20];

// Input the size of the array


printf("Enter the number of elements in the array: ");
scanf("%d", &n);

// Input the array elements (sorted in ascending order)


printf("Enter %d elements in sorted order:\n", n);
for (int i = 0; i < n; i++) {
9
Programming In C Module 2

scanf("%d", &arr[i]);
}

// Input the key to search for


printf("Enter the element to search for: ");
scanf("%d", &key);

// Binary Search
low = 0;
high = n - 1;
int found = 0; // Flag to indicate if key is found

while (low <= high) {


mid = (low + high) / 2; // Find the middle index

if (arr[mid] == key) {
printf("Element %d found at index %d.\n", key, mid);
found = 1;
break;
} else if (arr[mid] < key) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}

if (!found) {
printf("Element %d not found in the array.\n", key);
}

return 0;
}
Sample Output 1
Enter the number of elements in the array: 5 Enter 5
integers:
10 3 5 7 1
Enter an integer to search: 5

Element found at index: 2

Sample Output 2

Enter the number of elements in the array: 4 Enter 4


integers:
12 8 15 6
Enter an integer to search: 10

Element not found in the array.

10
Programming In C Module 2

5. Sort the given set of N numbers using Bubble sort.

Algorithm for Bubble Sort


1. First, we will select the range of the unsorted array. For that, we will run a loop(say
i) that will signify the last index of the selected range. The loop will run backward
from index n-1 to 0(where n = size of the array). The value i = n-1 means the range
is from 0 to n-1, and similarly, i = n-2 means the range is from 0 to n-2, and so on.
2. Within the loop, we will run another loop(say j, runs from 0 to i-1 though the range
is from 0 to i) to push the maximum element to the last index of the selected range,
by repeatedly swapping adjacent elements.
Basically, we will swap adjacent elements(if arr[j] > arr[j+1]) until the maximum element of the
range reaches the end.
3. Thus, after each iteration, the last part of the array will become sorted. Like: after
the first iteration, the array up to the last index will be sorted, and after the second
iteration, the array up to the second last index will be sorted, and so on.
4. After (n-1) iteration, the whole array will be sorted.

Iteration 1:

Iteration 2:

Iteration 3:

11
Programming In C Module 2

Iteration 4:

Iteration 5:

Program
#include <stdio.h>

int main() {
int n, i,arr[20],j,temp;

// Input the number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

// Input the array elements


printf("Enter %d elements:\n", n);
for ( i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Bubble Sort Algorithm


for ( i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

// Output the sorted array


printf("Sorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Sample Output:
Before Using Bubble Sort:
13 46 24 52 20 9
After Using bubble
12
Programming In C Module 2

sort: 9 13 20 24 46 52

6. Selection Sort

int main()
{
int n,i, temp, min;
int arr[20];
printf("Enter number of elements you want to sort: ");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("Enter %d Element: ",i+1); scanf("%d",&arr[i]);
}
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(arr[min]>arr[j])
min = j;
}
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
printf("After Selection sort elements are: ");
for (i=0; i<n;i++)
printf(“%d ”, arr[i]);

13
Programming In C Module 2

Two dimensional array


 It is a collection of data elements of same data type arranged in rows and columns. It
iscollection of one dimensional array.
 An array with two subscript is called two dimensional arrays. It enables us to store
multiplerows of elements such as table of values or matrix.
 Referring to Array Elements:
To access the elements of a two-dimensional array, we need a pair of indices: first
indexselects the row and the second index selects the column.

Syntax:
Datatype arrayname [size of row] [size of column];

Example: int A[3][2];


Col Col
0 1
Row 0 A[0][0] A[0][1]
Row 1 A[1][0] A[1][1]
Row 2 A[2][1] A[2][2]

i) Compile time initialization:


An two-dimensional array can be initialized along with declaration. For two-dimensional
array initialization,

elements of each row are enclosed within curly braces and separated by commas. All
rows are enclosed within curly braces.
Syntax:
datatype arrayname[size of row][size of column]={values separated by
comma};Example: int a[3][2]={{10,20},{30,40},{50,60}};

14
Programming In C Module 2

Col 0 Col 1

Row 0 10 20
Row 1 30 40
Row 2 50 60

Sample
program 4:
#include<stdio.h
>
#include<conio.h
> void main()
{
clrscr();
int a[3][2]={{10,20},{30,40},{50,60}};
printf(“%d\t”,a[0][0]);
printf(“%d\n”,a[0][1]);
printf(“%d\t”,a[1][0]);
printf(“%d\n”,a[1][1]);
printf(“%d\t”,a[2][0]);
printf(“%d\n”,a[2][1]);

}
Output:10 20
30 40
50 60

Sample program
#include<stdio.h>

#include<conio.h>voi
d main()
{
int a[3][2]={{10,20},{30,40},{50,60}};
int i,j;
printf("\nThe
Matrix");
for(i=0;i<2;i++)
{

printf("\n");
for(j=0;j<2;j++)
{

15
Programming In C Module 2

printf("\t%d",a[i][j]);
}
getch();
}

Output:
10 20
30 40
50 60

16
Programming In C Module 2

ii) Run time initialization: : Two-dimensional array can be initialization at run timeusing
loop.
int a[2][3];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}

Sample program :
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][3];int i,j;
printf(“Enter the elements\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}
printf(“\nThe elements
are”); for(i=0;i<2;i++)
{
printf(“\n”);
for(j=0;j<3;j++)
{

printf(“%d\t”, a[i][j]);
}
}
}

Enter the elements

17
Programming In C Module 2

1
2
3
4
The elements are

1 2
3 4
2. MATRIX ADDITION
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],b[2][2],c[2][2];
int i,j,k;
clrscr();
printf("Enter Matrix A");

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter matrix
B");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
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];
}
}

printf("\nThe result");
for(i=0;i<2;i++)

18
Programming In C Module 2

{
printf("\n");
for(j=0;j<2;j++)
{
printf("\t%d",c[i][j]);
}

}
getch();
}

Output:
Enter Matrix
A1 2 3 4

Enter Matrix
B1 2 3 4
The result2
4
6 8

3. MATRIX SUBTRACTION
#include<stdio.h>
#include<conio.h>
void main()

{
int a[2][2],b[2][2],c[2][2];
int i,j,k;
clrscr();
printf("Enter Matrix
A"); for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter matrix
B");
for(i=0;i<2;i++)
{

19
Programming In C Module 2

for(j=0;j<2;j++)
{
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];
}
}
printf("\nThe
result");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
{

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

Output:
Enter Matrix
A1 2 3 4
Enter Matrix B
1
1
1
1
Output:

01
2 3

20
Programming In C Module 2

4. MATRIX MULTIPLICATION

Input:
mat1[][] = {{1, 2},
{3, 4}}
mat2[][] = {{5, 6},
{7, 8}}
Multiplication of two matrices:
{{1*5 + 2*7 1*6 + 2*8},
{3*5 + 4*7 3*6 + 4*8}}

Output:
{{19, 22},
{43, 50}}
5.
Multiplication of two matrices is done by multiplying corresponding elements from the rows of the
first matrix with the corresponding elements from the columns of the second matrix and then adding
these products.

Note: The number of columns in the first matrix must be equal to the number of rows in the second
matrix.

Lab Prog. 4
4. Implement Matrix multiplication and validate the rules of multiplication
Input:
first[][] = {{1, 2}, {3, 4}}
second[][] = {{5, 6}, {7, 8}}
Multiplication of two matrices:
{{1*5 + 2*7 1*6 + 2*8},
{3*5 + 4*7 3*6 + 4*8}}
Output:
{{19, 22},
{43, 50}}
Multiplication of two matrices is done by multiplying corresponding elements from the rows of the
first matrix with the corresponding elements from the columns of the second matrix and then
adding these products.
Note: The number of columns in the first matrix must be equal to the number of rows in the second
matrix.
#include <stdio.h>

21
Programming In C Module 2

int main()
{
int m, n, p, q, i, j, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("\nEnter the number of rows and columns of first matrix:\n");
scanf("%d%d", &m, &n);
printf("\nEnter the number of rows and columns of second matrix:\n");
scanf("%d%d", &p, &q);
//Checking if Matrix Multiplication is possible
if ( n != p )
{
printf("\nMatrices with entered orders can't be multiplied with each other.\n");
printf("\nThe column of first matrix should be equal to row of second.\n");
}
else
{
//Entering elements of first matrix
printf("\nEnter the elements of first matrix:\n");
for ( i = 0 ; i< m ; i++ )
for ( j = 0 ; j < n ; j++ )
scanf("%d", &first[i][j]);
//Entering elements of second matrix
printf("\nEnter the elements of second matrix:\n");
for ( i = 0 ; i < p ; i++ )
for ( j= 0 ; j< q ; j++ )
scanf("%d", &second[i][j]);

22
Programming In C Module 2

//Carrying out matrix multiplication operation


for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < q ; j++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[i][k]*second[k][j];
}
multiply[i][j] = sum;
sum = 0;
}
}
//Printing the final product matrix
printf("\nThe product of entered matrices is:\n");
for ( i = 0 ; i < m ;i++ )
{
for ( j= 0 ; j < q ; j++ )
printf("%d\t", multiply[i][j]);
printf("\n");
}
}
return 0;
}

6. Program to print Transpose of matrix

#include<stdio.h>
#include<conio.h>void main()
{
int a[2][2] , i, j;
clrscr(); printf("Enter matrix A");
for(i=0;i<2;i++)
{
printf("\n"); for(j=0;j<2;j++)
{
printf("\t%d",a[i][j]);
}
}
printf("\nTranspose");

23
Programming In C Module 2

for(i=0;i<2;i++)
{
printf("\n"); for(j=0;j<2;j++)
{
printf("\t%d",a[j][i]);
}
}

getch();
}

Output:
Enter matrix A1 2
3 4
Transpose
1 3
2 4

24
Programming In C Module 2

Strings
 The group of characters, digits, & symbols enclosed within double quotes is called as Strings.
 Strings are actually one-dimensional array of characters terminated by a null character '\0'.
E.g. “INDIA” is a string. Each character of string occupies 1 byte of memory. The last
character isalways ‘\0’.

Declaration:

String is always declared as character arrays.

Syntax
char stringname[size];

E.g. char test [20];

Initialization:
We can use 2 ways for initializing.
1. By using string constant
E.g. char test[20]= “Hello”;
2. By using initialisation list
E.g. char test[20]={‘H’, ‘e’, ‘l’, ‘l’, ;o’, ‘\0’};

Read & write Strings in C using Printf() and Scanf() functions


#include <stdio.h>

int main()
{
char nickname[20];
printf("Enter your Nick
name:");scanf("%s",
nickname);
printf("Your Nick
name:%s",nickname); return 0;
25 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
Output:
Enter your Nick
name:Negan Your Nick
name:Negan

Read & Write Strings in C using gets() and puts() functions


#include
<stdio.h>
#include
<string.h> int
main()
{
char nickname[20];
puts("Enter your Nick
name:"); gets(nickname);
puts(nickname); return 0;
}

String Operations or String Functions

Function Description Syntax

Find the length of a string excluding ‘\0’ NULL


strlen(str);
strlen() character.

strcpy() Copies a string from the source to the destination. strcpy(dest, src);

strcat() Concatenate one string to the end of another. strcat(dest, src);

strcmp() Compares these two strings lexicographically. strcmp(s1, s2);

strstr() First occurrence of a substring in another string. strstr(s, subS);

strrev() Returns reversed string strrev(str)

26 by Pooja Shrivastav, Department of MCA


Programming In C Module 2

strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is not
counted.Syntax:
temp_variable = strlen (string_name);

#include
<stdio.h>
#include
<string.h> int
main()
{
char str1[20] = "Hello";
printf("Length of string str1: %d",
strlen(str1)); return 0;
}
Output:
Length of string str1: 5

Strlen() vs sizeof()
Strlen() returns you the length of the string stored in
array. sizeof() returns the total allocated size assigned
to the array.

i) String length without using string function


#include<stdio.
h>
#include<conio
.h> void main()
{
char str[100],temp;int
i=0,len=0; clrscr();
printf("\nEnter the string
:"); gets(str);
while(str[i])
{
len++;
i++;
}
printf("\nLength of string is :%d",len);
getch();
}

27 by Pooja Shrivastav, Department of MCA


Programming In C Module 2

1. strnlen(str,n)
It returns length of the string if it is less than the value specified for maxlen (maximum
length)otherwise it returns maxlen value.
Example:
#include
<stdio.h>
#include
<string.h> int
main()
{

char str1[20] = "welcome";


printf("Length of string str1 when maxlen is 10: %d\n", strnlen(str1,
10)); printf("Length of string str1 when maxlen is 5: %d\n", strnlen(str1,
5)); return 0;
}
Output:
Length of string str1 when maxlen is
10: 7 Length of string str1 when
maxlen is 5: 5

2. strcmp() function
It is used to compare 2
strings temp_varaible=strcmp(string1,string2)

 If the first string is greater than the second string a positive number is returned.
 If the first string is less than the second string a negative number is returned.
 If the first and the second string are equal 0 is returned.

Example:
#include
<stdio.h>
#include
<string.h> int
main()
{
char s1[20] = "Hello";
char s2[20] = "Hello";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
28 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
}

else
{
printf("string 1 and 2 are different");
}
return 0;
}

//String Compare without built in function


#include <stdio.h>

int main() {
char str1[100], str2[100];
int i, flag = 0;

printf("Enter the first string: ");


scanf("%s", str1);

printf("Enter the second string: ");


scanf("%s", str2);

// Compare strings character by character


for (i = 0; str1[i] != '\0' && str2[i] != '\0'; i++) {
if (str1[i] != str2[i]) {
flag = 1;
break;
}
}

// Check if strings are equal or not


if (flag == 0 && str1[i] == '\0' && str2[i] == '\0') {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}

return 0;
}
3. Strncmp(str1,str2)

It compares both the string till n characters or in other words it compares first n characters of
boththe strings. #include <stdio.h>
29 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
#include
<string.h> int
main()
{
char s1[20] =
"Hello"; char s2[20]
= "Hello";
if (strncmp(s1, s2,4) ==0)
{
printf("string 1 and string 2 are equal");
}else
{

printf("string 1 and 2 are different");


}
return 0;
}

4. strcpy() function
It copies the source string to the destination
string Syntax
strcpy(destination,source);

#include
<stdio.h>
#include
<string.h> int
main()
{
char s1[30] = "string
1"; char s2[30] = " New
String"; strcpy(s1,s2);
printf("String s1 is: %s",
s1); return 0;
}
//String Copy without Built in function
#include <stdio.h>
int main() {
char s1[100], s2[100], i;
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin);

for (i = 0; s1[i] != '\0'; ++i) {


s2[i] = s1[i];
}
30 by Pooja Shrivastav, Department of MCA
Programming In C Module 2

s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}

5. strncpy(s1,s2)
Case1: If length of str2 > n then it just copies first n characters of str2 into
str1. Case2: If length of str2 < n then it copies all the characters of str2 into str1 and
appends several terminator chars(‘\0’) to accumulate the length of str1 to make it n.
#include
<stdio.h>
#include
<string.h> int
main()
{
char s1[10] = "Hello";
char s2[10] =
"welcome";
strncpy(s1,s2,5);
printf("String s1 is: %s",
s1); return 0;

6. strchr(str) / strrchr(str)
It searches string str for character ch.
#include
<stdio.h>
#include
<string.h> int
main()
{
char mystr[30] = "Hai! Hello!
Welcome! ";
printf ("%s", strchr(mystr, 'W'));
return 0;
}

7. strstr(str,search)
It is similar to strchr, except that it searches for string srch_term instead of a single char.
#include<stdio.h>
#include <string.h>
int main()

31 by Pooja Shrivastav, Department of MCA


Programming In C Module 2
{
char mystr[30] = "Hai! Hello! Welcome! ";
printf ("%s", strstr(mystr, "Hello"));
return 0;
}

//search for a substring in a string without built in function


#include <stdio.h>
int main() {
char str[100], substr[50];
int i, j, k, found = 0;
printf("Enter the string: ");
scanf("%s", str);
printf("Enter the substring to search: ");
scanf("%s", substr);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == substr[0]) {
j = i;
k = 0;

while (str[j] == substr[k] && substr[k] != '\0') {


j++;
k++;
}
if (substr[k] == '\0') {
found = 1;
break;
}
}
}
if (found) {
printf("Substring found in the string.\n");
} else {
printf("Substring not found in the string.\n");
}
return 0;
}

8. strcat() function
It concatenates a second string to the end of the first
string. #include <stdio.h>
#include strcat(firststring, secondstring);
<string.h> int
main()
{
char s1[10] = "Hello";
char s2[10] = "World";
32 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}

Concatenating two string without using string function

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

char s1[50], s2[30];


int i,j=0;
clrscr();
printf("\nEnter String 1 :");
gets(s1);
printf("\nEnter String 2 :");
gets(s2);
i = strlen(s1);
while(s2[j]!='\0')
{
s1[i]=s2[j];
i++;
j++;
}
s1[i] = '\0';
printf("\nconcatenad string is:%s",s1);
getch();
}
output:

Enter String 1:computer


Enter String 2:programming
Concated string is : computerprogramming

9. strlwr() function
It converts all the uppercase characters in that string to lowercase characters.
#include
<stdio.h>
#include
<string.h> int
main()
{
33 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
char mystr[30] = "HAI HELLO WELCOME! ";
printf("%s",
strlwr(mystr)); return 0;
}
10. strupr() function
It converts all the lowercase characters in that string to uppercase characters.
#include
<stdio.h>
strupr(string_name);
#include
<string.h> int
main()
{
char mystr[30] = "Hai Hello
Welcome! "; printf("%s",
strupr(mystr));

return 0;
}
11. strrev() function
It is used to reverse the string.
Syntax strrev(string_name);
#include <stdio.h>
#include <string.h>
int main()
{

char mystr[30] = "Welcome! ";


printf("%s", strrev(mystr));
return 0;
}

34 by Pooja Shrivastav, Department of MCA


Programming In C Module 2

ii) String reverse without using string function

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str[100];
int length, i;
printf("Enter a string: ");
scanf("%s", str);
length = strlen(str);
printf("Reversed string: ");
for ( i = length - 1; i >= 0; i--)
{
printf("%c", str[i]);
}
printf("\n");

return 0;
}
}
output

Enter the string:c program


Reverse string is:margop c

String Arrays

They are used to store multiple strings. 2-D char array is used for string arrays.

Declaration
char arrayname[rowsize][colsize];
E.g.
char s[2][30];
Here, s can store 2 strings of maximum 30 characters each.
Initialization
2 ways
1. Using string constants
char s[2][20]={“Ram”, “Sam”};

35 by Pooja Shrivastav, Department of MCA


Programming In C Module 2

2. Using initialization list.


char s[2][20]={ {‘R’, ‘a’, ‘m’, ‘\0’},
{‘S’, ‘a’, ‘m’, ‘\0’}};
E.g. Program
#include<stdio.h>
void main()
{
int i;
char s[3][20];
printf("Enter Names\n");
for(i=0;i<3;i++)
scanf("%s", s[i]);
printf("Student Names\n");
for(i=0;i<3;i++)
printf("%s\n", s[i]);
}

Array of Strings

Syntax:

 The list of strings are stored by using two dimensional character array is termed as string of arrays.

datatype arrayname[row-size][column-size];

row-size: number of string


column-size: maximum number of character in each string

Example:
char a[4][7];
//it can store 4 strings and each string stores maximum 7
charactersInitialization of String of Array:

char A[4][5]={“Ram”,”Raj”,”Ravi”,”Jai”};

A[0] R a m \0
A[1] R a j \0
A[2] R a v i \0
A[3] J a i \0

36 by Pooja Shrivastav, Department of MCA


Programming In C Module 2
2. Example Program For Sorting Of String In C Language
#include <stdio.h>
#include <string.h>

int main() {
char name[25][50], temp[25];
int n, i, j;

printf("Input number of strings: ");


scanf("%d", &n);

printf("Input string %d :\n", n);


for (i = 0; i <= n; i++)
{
scanf(“%s”,name[i]);
}

/* Logic for Bubble Sort */


for (i = 1; i < n-1; i++) {
for (j = 0; j <= n – i-1; j++) {
if (strcmp(name[j], name[j + 1]) > 0)
{
strcpy(temp, name[j]);
strcpy(name[j], name[j + 1]);
strcpy(name[j + 1], temp);
}
}
}

printf("The sorted strings :\n");


for (i = 0; i <= n; i++) {
printf("%s\n", name[i]);

return 0;
}
}
Output:

Input number of strings 3


Input string
Php
Mysql
C program

The sorted strings


C program
Mysql
Php

37 by Pooja Shrivastav, Department of MCA


Programming In C Module 2

i) Program to convert upper case string to lower case string without using string
function

#includ
e<stdio.
h>
#includ
e<conio
.h> void
main()
{
char
s1[20],lower[20];
int i=0;
clrscr();
printf("\nEnter the string in upper case:");
gets(s1);
while(s1[i])
{
if(s1[i]>='A' &&
s1[i]<='Z')
lower[i]=s1[i]+32;
else
lower[i]=s1[i];
i++;

lower[i]='\0'; printf("\nLower String");


puts(lower);
getch();

Output:
Enter the string in upper case: C PROGRAM
Lower String c program

ii) Converting lower case string to upper case string without using string function

#includ
e<stdio.
h>
#includ
e<conio
.h> void
main()

38
Programming In C Module 2

{
char s1[20],upper[20];
int i=0;
clrscr();
printf("\nEnter the string:");
gets(s1);
while(s1[i])
{
if(s1[i]>='a'
&&
s1[i]<='z')
upper[i]=s
1[i]-32;
else
uppe
r[i]
=s1[
i];
i++;
}
upper[i]='\0'; printf("\nUpper String");
puts(upper);
getch();

}
output:

Enter the string in lower case: c program upper

String C PROGRAM

Pogram To Count The Number Of Words In a String


#include<stdio.h>
#include<conio.h>
void main()
{
char str[100];
int i,count=0;
clrscr();
printf("\nenter the string\n");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(str[i]== ' ' )
count++;

39
Programming In C Module 2

}
printf("The number of words is %d",count+1);
getch();
}
Output:

40

You might also like