0% found this document useful (0 votes)
25 views52 pages

CS8251 UNIT II Notes

This document covers arrays and strings in C programming, detailing their declaration, initialization, and operations. It includes example programs for calculating mean, median, mode, and performing matrix operations. Additionally, it discusses single and two-dimensional arrays, providing syntax and examples for various array manipulations.

Uploaded by

Sundari
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)
25 views52 pages

CS8251 UNIT II Notes

This document covers arrays and strings in C programming, detailing their declaration, initialization, and operations. It includes example programs for calculating mean, median, mode, and performing matrix operations. Additionally, it discusses single and two-dimensional arrays, providing syntax and examples for various array manipulations.

Uploaded by

Sundari
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/ 52

CS8251 Programming in C – UNIT II

UNIT II ARRAYS AND STRINGS


Introduction to Arrays: Declaration, Initialization – One dimensional array –
Example Program: Computing Mean, Median and Mode - Two dimensional arrays
– Example Program: Matrix Operations (Addition, Scaling, Determinant and
Transpose) - String operations: length, compare, concatenate, copy – Selection sort,
linear and binary search

2.1 INTRODUCTION TO ARRAYS


An Array is a collection of similar data elements. These data elements have the
same data type. The elements of the array are stored in consecutive memory locations and
are referenced by an index (also known as subscript). Subscript indicates an ordinal
number of the elements counted from the beginning of the array.
Definition:
An array is a data structure that is used to store data of the same type. The position of an
element is specified with an integer value known as index or subscript.
E.g.
a(integer array) 1 3 5 2

1.2 3.5 5.4 2.1


b(float array )
[0] [1] [2] [3]

Characteristics:
i) All the elements of an array share a common name called as array name
ii) The individual elements of an array are referred based on their position.
iii) The array index in c starts with 0.
In general arrays are classified as:
1. Single dimensional array
2. Multi-dimensional array

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 1


CS8251 Programming in C – UNIT II

2.1.1 Declarations of Arrays


Array has to be declared before using it in C Program. Declaring Array means specifying
three things.
Data_type Data Type of Each Element of the array
Array_name Valid variable name
Size Dimensions of the Array
Arrays are declared using the following syntax:
type name[size]
Here the type can be either int, float, double, char or any other valid data type. The
number within the brackets indicates the size of the array, i.e., the maximum number of
elements that can be stored in the array.
ex: int marks[10]

2.1.2 Initialization of arrays


Elements of the array can also be initialized at the time of declaration as in the
case of every other variable. When an array is initialized, we need to provide a value for
every element in the array. Arrays are initialized by writing,
type array_name[size] = { list of values};
The values are written with curly brackets and every value is separated by a comma. It is
a compiler error to specify more number of values than the number of elements in the
array.
ex: int marks[5] = {90, 92, 78, 82, 58};

2.4 One dimensional Array


 It is also known as one-dimensional arrays or linear array or vectors
 It consists of fixed number of elements of same type
 Elements can be accessed by using a single subscript.
eg) a[2]=9;
Eg)

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 2


CS8251 Programming in C – UNIT II

a 1 3 5 2

[0] [1] [2] [3] subscripts or indices

Declaration of Single Dimensional Array


Syntax:
datatype arrayname [array size];

E.g. int a[4]; // a is an array of 4 integers


char b[6]; //b is an array of 6 characters

Initialization of single dimensional array


Elements of an array can also be initialized.
Rules
a) Elements of an array can be initialized by using an initialization list. An initialization
list is a comma separated list of initializers enclosed within braces.
Eg) int a[3]={1,3,4};
b) If the number of initializers in the list is less than array size, the leading array locations
gets initialized with the given values. The rest of the array locations gets initialized to
0 - for int array
0.0 - for float array
\0 - for character array
Eg) int a[2]={1};
a 1 0

char b[5]={‘A’.’r’,’r’};

b ‘A’ ‘r’ ‘r’ ‘\0’ ‘\0’

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 3


CS8251 Programming in C – UNIT II

Usage of single dimensional array


The elements of single dimensional array can be accessed by using a subscript
operator([]) and a subscript.

Reading storing and accessing elements:


An iteration statement (i.e loop) is used for storing and reading elements.

Ex:1 Program to calculate the average marks of the class


#include <stdio.h>
void main()
{
int m[5],i,sum=0,n;
float avg;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
avg=(float)sum/n;
printf(“average=%f”,avg);
}
Output:
Enter number of students
5
Enter marks of students

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 4


CS8251 Programming in C – UNIT II

55
60
78
85
90
Average=73.6

2.5 Example Programs


1. C Program to Find Mean, Median, and Mode of Given Numbers.
#define SIZE 100
#include"stdio.h"
float mean_function(float[],int);
float median_function(float[],int);
float mode_function(float[],int);
int main()
{
int i,n,choice;
float array[SIZE],mean,median,mode;
printf("Enter No of Elements\n");
scanf("%d",&n);
printf("Enter Elements\n");
for(i=0;i
scanf("%f",&array[i]);
do
{
printf("\n\tEnter Choice\n\t1.Mean\n\t2.Median\n\t3.Mode\n4.Exit");
scanf("%d",&choice);
switch(choice)
{

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 5


CS8251 Programming in C – UNIT II

case 1: mean=mean_function(array,n);
printf("\n\tMean = %f\n",mean);
break;
case 2: median=median_function(array,n);
printf("\n\tMedian = %f\n",median);
break;
case 3: mode=mode_function(array,n);
printf("\n\tMode = %f\n",mode);
break;
case 4: break;
default:printf("Wrong Option");
break;
}
}while(choice!=4);
}
float mean_function(float array[],int n)
{
int i;
float sum=0;
for(i=0;i
sum=sum+array[i];
return (sum/n);
}
float median_function(float a[],int n)
{
float temp;
int i,j;
for(i=0;i
for(j=i+1;j

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 6


CS8251 Programming in C – UNIT II

{
if(a[i]>a[j])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
if(n%2==0)
return (a[n/2]+a[n/2-1])/2;
else
return a[n/2];
}
float mode_function(float a[],int n)
{
return (3*median_function(a,n)-2*mean_function(a,n));
}
Output
Enter Elements
2
3
4

Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
1

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 7


CS8251 Programming in C – UNIT II

Mean = 3.000000

Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
2

Median = 3.000000

Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
3

Mode = 3.000000

Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
4

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 8


CS8251 Programming in C – UNIT II

2. C program to calculate the sum of array


#include<stdio.h>
int main() {
int i, arr[50], sum, num;
printf("\n Enter no of elements :");
scanf("%d", &num);

//Reading values into Array


printf("\n Enter the values :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);

//Computation of total
sum = 0;
for (i = 0; i < num; i++)
sum = sum + arr[i];

//Printing of all elements of array


for (i = 0; i < num; i++)
printf("\n a[%d]=%d", i, arr[i]);

//Printing of total
printf("\nSum=%d", sum);

return (0);
}
Output:
Enter no of elements: 5
Enter the values: 67 89 56 78 90

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor 9


CS8251 Programming in C – UNIT II

a[0]=67
a[1]=89
a[2]=56
a[3]=78
a[4]=90
Sum= 380

3. C program to find the largest array element


#include <stdio.h>
int main() {
int i, n;
float arr[100];
printf("Enter the number of elements (1 to 100): ");
scanf("%d", &n);
for (i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%f", &arr[i]);
}
// storing the largest number to arr[0]
for (i = 1; i < n; ++i) {
if (arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
return 0;
}
Output:
Enter the number of elements (1 to 100): 5

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


10
CS8251 Programming in C – UNIT II

Enter number1: 67
Enter number2: 90
Enter number3: 45
Enter number4: 89
Enter number5: 47
Largest element = 90

4. C program to copy the elements of one array into another array


#include <stdio.h>
void main()
{
int arr1[100], arr2[100];
int i, n;
printf("\n\nCopy the elements one array into another array :\n");
printf("----------------------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
/* Copy elements of first array into second array.*/
for(i=0; i<n; i++)
{
arr2[i] = arr1[i];
}

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


11
CS8251 Programming in C – UNIT II

/* Prints the elements of first array */


printf("\nThe elements stored in the first array are :\n");
for(i=0; i<n; i++)
{
printf("% 5d", arr1[i]);
}

/* Prints the elements copied into the second array. */


printf("\n\nThe elements copied into the second array are :\n");
for(i=0; i<n; i++)
{
printf("% 5d", arr2[i]);
}
printf("\n\n");
}
Output:
Copy the elements one array into another array :
----------------------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 15
element - 1 : 10
element - 2 : 12

The elements stored in the first array are :


15 10 12

The elements copied into the second array are :

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


12
CS8251 Programming in C – UNIT II

15 10 12

2.6 Two dimensional Array


 A 2D array is an array of 1-D arrays and can be visualized as a plane that has rows
and columns.
 The elements can be accessed by using two subscripts, row subscript (row no),
column subscript(column no).
 It is also known as matrix.
E.g,
1 2 3 6 7
9 10 5 0 4
a[3][5] 3 1 2 1 6

Declaration
datatype arrayname [row size][column size]

e.g) int a [2][3]; //a is an integer array of 2 rows and 3 columns


number of elements=2*3=6

Initialization
1. By using an initialization list, 2D array can be initialized.
e.g. int a[2][3] = {1,4,6,2}
a
1 4 6
2 0 0

2. The initializers in the list can be braced row wise.


e.g int a[2][3] = {{1,4,6} , {2}};

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


13
CS8251 Programming in C – UNIT II

2.7 Example Programs


1. C Program to Find the Addition of two Matrix
#include<stdio.h>
void addition(int m[3][3], int n[3][3]);
int main()
{
int a[3][3], b[3][3], i, j;
// take first matrix
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("Enter a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\n");

// take second matrix


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("Enter b[%d][%d]:",i,j);

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


14
CS8251 Programming in C – UNIT II

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

// print first matrix (Optional)


printf("\nEntered first matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n"); // new line
}

// print second matrix (Optional)


printf("Entered second matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n"); // new line
}

addition(a,b); // matrix a and b passed


return 0;

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


15
CS8251 Programming in C – UNIT II

void addition(int m[3][3], int n[3][3])


{
int sum[3][3], i, j;

// add both matrices


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum[i][j] = m[i][j] + n[i][j];
}
}

// print resultant matrix


printf("\nAddition of both Matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",sum[i][j]);
}
printf("\n"); // new line
}
}
Output:-

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


16
CS8251 Programming in C – UNIT II

Enter a[0][0]:12
Enter a[0][1]:13
Enter a[0][2]:25
Enter a[1][0]:32
Enter a[1][1]:14
Enter a[1][2]:20
Enter a[2][0]:32
Enter a[2][1]:25
Enter a[2][2]:18

Enter b[0][0]:29
Enter b[0][1]:26
Enter b[0][2]:27
Enter b[1][0]:35
Enter b[1][1]:42
Enter b[1][2]:50
Enter b[2][0]:12
Enter b[2][1]:9
Enter b[2][2]:23

Entered first matrix is:


12 13 25
32 14 20
32 25 18
Entered second matrix is:
29 26 27
35 42 50
12 9 23

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


17
CS8251 Programming in C – UNIT II

Addition of both Matrix is:


41 39 52
67 56 70
44 34 41

2. C Program to Subtract Two Matrices

#include<stdio.h>
int main()
{
int i, j, rows, columns, a[10][10], b[10][10];
int Subtraction[10][10];
printf("\n Please Enter Number of rows and columns : ");
scanf("%d %d", &i, &j);
printf("\n Please Enter the First Matrix Elements\n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0;columns < j;columns++)

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


18
CS8251 Programming in C – UNIT II

{
scanf("%d", &a[rows][columns]);
}
}
printf("\n Please Enter the Second Matrix Elements\n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0;columns < j;columns++)
{
scanf("%d", &b[rows][columns]);
}
}
for(rows = 0; rows < i; rows++)
{
for(columns = 0;columns < j;columns++)
{
Subtraction[rows][columns] = a[rows][columns] - b[rows][columns];
}
}
printf("\n After Subtracting Matrix a from Matrix b = a - b \n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
printf("%d \t ", Subtraction[rows][columns]);
}
printf("\n");
}

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


19
CS8251 Programming in C – UNIT II

return 0;
}
Output:
Please Enter Number of rows and columns : 2 3
Please Enter the First Matrix Elements
10 20 30
40 50 60
Please Enter the Second Matrix Elements
25 95 65
75 12 100
After Subtracting Matrix a from Matrix b = a - b
-15 -75 -35
-35 38 -40

3. C Program to Find Multiplication of two Matrix

#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


20
CS8251 Programming in C – UNIT II

system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


21
CS8251 Programming in C – UNIT II

for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


22
CS8251 Programming in C – UNIT II

multiply of the matrix=


666
12 12 12
18 18 18

4. Program to Find the Transpose of a Matrix


#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

// Assigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// Displaying the matrix a[][]


printf("\nEntered matrix: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


23
CS8251 Programming in C – UNIT II

// Finding the transpose of matrix a


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}

// Displaying the transpose of matrix a


printf("\nTranspose of the matrix:\n");
for (i = 0; i < c; ++i)
for (j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}
Output
Enter rows and columns: 2
3

Enter matrix elements:


Enter element a11: 1
Enter element a12: 4
Enter element a13: 0
Enter element a21: -5
Enter element a22: 2
Enter element a23: 7

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


24
CS8251 Programming in C – UNIT II

Entered matrix:
1 4 0
-5 2 7

Transpose of the matrix:


1 -5
4 2
0 7

5. Program to Compute Determinant of a Matrix

#include <stdio.h>
void main()
{
int arr1[10][10],i,j,n;
int det=0;

printf("\n\nCalculate the determinant of a 3 x 3 matrix :\n");


printf("-------------------------------------------------\n");

printf("Input elements in the first matrix :\n");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


25
CS8251 Programming in C – UNIT II

}
}
printf("The matrix is :\n");
for(i=0;i<3;i++)
{
for(j=0;j<3 ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}
for(i=0;i<3;i++)
det = det + (arr1[0][i]*(arr1[1][(i+1)%3]*arr1[2][(i+2)%3] -
arr1[1][(i+2)%3]*arr1[2][(i+1)%3]));
printf("\nThe Determinant of the matrix is: %d\n\n",det);
}
Output:
Calculate the determinant of a 3 x 3 matrix :
-------------------------------------------------
Input elements in the first matrix :
element - [0],[0] : 1
element - [0],[1] : 0
element - [0],[2] : -1
element - [1],[0] : 0
element - [1],[1] : 0
element - [1],[2] : 1
element - [2],[0] : -1
element - [2],[1] : -1
element - [2],[2] : 0
The matrix is :

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


26
CS8251 Programming in C – UNIT II

1 0 -1
0 0 1
-1 -1 0

The Determinant of the matrix is: 1

2.8 String Operations


Definition:
The group of characters, digits, & symbols enclosed within double quotes is called as
Strings. Every string is terminated with the NULL (‘\0’) character.
E.g. “INDIA” is a string. Each character of string occupies 1 byte of memory. The
last character is always ‘\0’.
Declaration:
String is always declared as character arrays.
Syntax
char stringname[size];

E.g. char a[20];


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

2.9 String Operations or String Functions


These functions are defined in string.h header file.
1. strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is not counted.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


27
CS8251 Programming in C – UNIT II

Syntax

temp_variable = strlen(string_name);

E.g.
s= “hai”;
strlen(s)-> returns the length of string s i.e. 3.
2. strcpy() function
It copies the source string to the destination string
Syntax

strcpy(destination,source);

E.g.
s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); -> s2 is copied to s1. i.e. s1=welcome.
3. strcat() function
It concatenates a second string to the end of the first string.
Syntax

strcat(firststring, secondstring);

E.g.
s1=“hai ”;
s2= “welcome”;
strcat(s1,s2); -> s2 is joined with s1. Now s1 is hai welcome.
E.g. Program:
#include <stdio.h>
#include <string.h>

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


28
CS8251 Programming in C – UNIT II

void main ()
{
char str1[20] = "Hello";
char str2[20] = "World";
char str3[20];
int len ;
strcpy(str3, str1);
printf("Copied String= %s\n", str3 );
strcat( str1, str2);
printf("Concatenated String is= %s\n", str1 );
len = strlen(str1);
printf("Length of string str1 is= %d\n", len );
return 0;
}
Output:
Copied String=Hello
Concatenated String is=HelloWorld
Length of string str1is

4. strcmp() function
It is used to compare 2 strings.
Syntax
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.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


29
CS8251 Programming in C – UNIT II

5. strlwr() function
It converts all the uppercase characters in that string to lowercase characters.
Syntax

strlwr(string_name);

E.g.
str[10]= “HELLO”;
strlwr(str);
puts(str);
Output: hello

6. strupr() function
It converts all the lowercase characters in that string to uppercase characters.
Syntax

strupr(string_name);

E.g.
str[10]= “HEllo”;
strupr(str);
puts(str);
Output: HELLO

7. strrev() function
It is used to reverse the string.
Syntax

strrev(string_name);

E.g.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


30
CS8251 Programming in C – UNIT II

str[10]= “HELLO”;
strrev(str);
puts(str);
Output: OLLEH

String functions
Functions Descriptions
strlen() Determines the length of a String
strcpy() Copies a String from source to destination
strcmp() Compares two strings
strlwr() Converts uppercase characters to lowercase
strupr() Converts lowercase characters to uppercase
strdup() Duplicates a String
strstr() Determines the first occurrence of a given String in another string
strcat() Appends source string to destination string
strrev() Reverses all characters of a string

Example: String Comparison


void main()
{
char s1[20],s2[20];
int val;
printf(“Enter String 1\n”);
gets(s1);
printf(“Enter String 2\n”);
gets (s2);
val=strcmp(s1,s2);
if (val==0)

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


31
CS8251 Programming in C – UNIT II

printf(“Two Strings are equal”);


else
printf(“Two Strings are not equal”);
getch();
}
Output:
Enter String 1
Computer
Enter String 2
Programming
Two Strings are not equal

Example: String Length


#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
// using the %zu format specifier to print size_t
printf("Length of string a = %zu \n",strlen(a));
printf("Length of string b = %zu \n",strlen(b));
return 0;
}
Output
Length of string a = 7
Length of string b = 7

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


32
CS8251 Programming in C – UNIT II

Example: String Copy


#include<stdio.h>
#include<string.h>
int main() {
char str1[100];
char str2[100];
printf("\nEnter the String 1 : ");
gets(str1);
strcpy(str2, str1);
printf("\nCopied String : %s", str2);
return (0);
}
Output:
Enter the String 1 : Programming
Copied String : Programming

Example: String concatenate


#include <stdio.h>
#include <string.h>
main()
{
char s1[20], s2[20];
printf("\nEnter first string: ");
gets(s1);
printf("\nEnter second string: ");
gets(s2);
strcat(s1, s2);
printf("\nThe concatenated string is: %s", s1);

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


33
CS8251 Programming in C – UNIT II

getch();
}
OUTPUT:
Enter first string: Programming
Enter second string: .com
The concatenated string is: Programming.com

Example: String reversion


#include <stdio.h>
#include <string.h>
int main()
{
char s[100];
printf("Enter a string to reverse: \n");
gets(s);
strrev(s);
printf("Reverse of the string: %s\n", s);
return 0;
}
Output:
Enter a string to reverse: String
Reverse of the string:gnirts

Programs on Strings
1. To count total number of alphabets, digits and special characters in a string
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


34
CS8251 Programming in C – UNIT II

#define str_size 100 //Declare the maximum size of the string


void main()
{
char str[str_size];
int alp, digit, splch, i;
alp = digit = splch = i = 0;
printf("\n\nCount total number of alphabets, digits and special characters :\n");
printf("--------------------------------------------------------------------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);
/* Checks each character of string*/
while(str[i]!='\0')
{
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
{
alp++;
}
else if(str[i]>='0' && str[i]<='9')
{
digit++;
}
else
{
splch++;
}
i++;
}
printf("Number of Alphabets in the string is : %d\n", alp);

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


35
CS8251 Programming in C – UNIT II

printf("Number of Digits in the string is : %d\n", digit);


printf("Number of Special characters in the string is : %d\n\n", splch);
}
Output:
Count total number of alphabets, digits and special characters :
--------------------------------------------------------------------
Input the string : Welcome to C4\\
Number of Alphabets in the string is : 10
Number of Digits in the string is : 1
Number of Special characters in the string is : 4

2. To count total number of vowel or consonant in a string


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define str_size 100 //Declare the maximum size of the string
void main()
{
char str[str_size];
int i, len, vowel, cons;
printf("\n\nCount total number of vowel or consonant :\n");
printf("----------------------------------------------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);

vowel = 0;
cons = 0;
len = strlen(str);

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


36
CS8251 Programming in C – UNIT II

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


{
if(str[i] =='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' || str[i]=='A' ||
str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U')
{
vowel++;
}
else if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
{
cons++;
}
}
printf("\nThe total number of vowel in the string is : %d\n", vowel);
printf("The total number of consonant in the string is : %d\n\n", cons);
}
Output:
Count total number of vowel or consonant :
----------------------------------------------
Input the string : abcdf

The total number of vowel in the string is : 4


The total number of consonant in the string is : 4

3. To sort names in an alphabetical order


#include<stdio.h>
#include<string.h>
int main(){
int i,j,count;

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


37
CS8251 Programming in C – UNIT II

char str[25][25],temp[25];
puts("How many strings u are going to enter?: ");
scanf("%d",&count);
puts("Enter Strings one by one: ");
for(i=0;i<=count;i++)
gets(str[i]);
for(i=0;i<=count;i++)
for(j=i+1;j<=count;j++){
if(strcmp(str[i],str[j])>0){
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("Order of Sorted Strings:");
for(i=0;i<=count;i++)
puts(str[i]);
return 0;
}

Output:
How many strings u are going to enter?
5
Enter Strings one by one:
Ajith
Ravi
Kelvin
Divya

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


38
CS8251 Programming in C – UNIT II

Bhavana
Order of Sorted Strings:
Ajith
Bhavana
Divya
Kelvin
Ravi

2.8.1 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”};
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];

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


39
CS8251 Programming in C – UNIT II

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”, s[i]);
}

2.9 Sorting
Sorting is the process of arranging elements either in ascending or in descending order.
Sorting Methods
1. Selection Sort
2. Bubble Sort
3. Merge sort
4. Quick sort

1. Selection sort
It finds the smallest element in the list & swaps it with the element present at the
head of the list.
E.g.
25 20 15 10 5
5 20 15 10 25
5 10 15 20 25

2. Bubble Sort
In this method, each data item is compared with its neighbour element. If they are
not in order, elements are exchanged.
With each pass, the largest of the list is "bubbled" to the end of the list.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


40
CS8251 Programming in C – UNIT II

E.g.
Pass 1:
25 20 15 10 5
20 25 15 10 5
20 15 25 10 5
20 15 10 25 5
20 15 10 5 25
25 is the largest element
Repeat same steps until the list is sorted

3. Merge Sort:
 Merge sort is based on Divide and conquer method.
 It takes the list to be sorted and divide it in half to create two unsorted lists.
 The two unsorted lists are then sorted and merged to get a sorted list.

4. Quick Sort

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


41
CS8251 Programming in C – UNIT II

 This method also uses the technique of ‘divide and conquer’.


 Pivot element is selected from the list, it partitions the rest of the list into two parts
– a sub-list that contains elements less than the pivot and other sub-list containing
elements greater than the pivot.
 The pivot is inserted between the two sub-lists. The algorithm is recursively
applied to sort the elements.

Program:
#include <stdio.h>
void main()
{
int i, j, temp, n, a[10];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


42
CS8251 Programming in C – UNIT II

for (j = i + 1; j < n; j++)


{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; i++)
printf("%d\n", a[i]);
printf("The numbers arranged in descending order are given below \n");
for(i=n-1;i>=0;i--)
printf("%d\n",a[i]);
}
Output:
Enter the value of N
4
Enter the numbers
10 2 5 3
The numbers arranged in ascending order are given below
2
3
5
10
The numbers arranged in descending order are given below

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


43
CS8251 Programming in C – UNIT II

10
5
3
2

2.10 Searching
Searching is an operation in which a given list is searched for a particular value. If
the value is found its position is returned.
Types:
1. Linear Search
2. Binary Search
1. Linear Search
The search is linear. The search starts from the first element & continues in a
sequential fashion till the end of the list is reached. It is slower method.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,m,c=0;
clrscr();
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


44
CS8251 Programming in C – UNIT II

scanf("%d",&m);
for(i=0;i<=n-1;i++)
{
if(a[i]==m)
{
printf("Element is in the position %d\n",i+1);
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
getch();
}

Output:
Enter the size of an array: 4
Enter the elements of the array: 4 3 5 1
Enter the number to be search: 5
Element is in the position 3

2. Binary Search
 If a list is already sorted then we can easily find the element using binary
serach.
 It uses divide and conquer technique.
Steps:
1. The middle element is tested with searching element. If found, its position is
returned.

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


45
CS8251 Programming in C – UNIT II

2. Else, if searching element is less than middle element, search the left half else
search the right half.
3. Repeat step 1 & 2.
Program:
#include<stdio.h>
void main()
{
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
}

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


46
CS8251 Programming in C – UNIT II

else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
}
Sample output:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21
Enter the number to be search: 11
The number is found.
Example:
3 5 7 9 11
Search key=7 middle element=7
Searching element=middle element. So the element is found.
Search key=11
Middle element=7
Searching element>middle
So go to right half: 9 11. Repeat steps until 11 is found or list ends.

MULTIPLE CHOICE QUESTIONS


1. An array is a collection of
A. Similar data elements
B. functions
C. values

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


47
CS8251 Programming in C – UNIT II

Answer: A

2. If an array is declared as arr[]={1,3,5,7,9}; then what is the value of


sizeof(arr[3])?
A. 1
B. 2
C. 8
D. 3
Answer: B

3. If an array is declared as arr[]={1,3,5,7,9}; then what is the value of arr[3]?


A. 1
B. 2
C. 7
D. 3
Answer: C

4. What will be the address of the arr[2][3] if arr is a 2-D long array of 4 rows and 5
columns and starting address of the array is 2000?
A. 2048
B. 2056
C. 2052
D. 2042
Answer: 2052

5. The parameter passing mechanism for an array is


A. call by value
B. call by reference

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


48
CS8251 Programming in C – UNIT II

C. call by value-result
D. None of the above
Answer: call by reference

6. Which of the following function is more appropriate for reading in a multi-word


string?
A. scanf()
B. printf()
C. gets()
D. puts()
Answer: gets()
7. LENGTH (‘0’) =
A. -1
B. 0
C. 1
D. None of These
Answer : 0

8. ASCII code for a-z ranges from

A. 0-26
B. 35-81
C. 97-123
D. None of These
Answer : 97-123

9. Insert(“XXXYYYZZZ”,1, “PPP”) =
A. PPPXXXYYYZZZ

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


49
CS8251 Programming in C – UNIT II

B. XPPPXXYYYZZZ
C. XXXYYYZZZPPP

Answer : XPPPXXYYYZZZ

10. Delete (“XXXYYYZZZ”,4,3) =


A. XXYZ
B. XXXYYZZ
C. XXXYZZ

Answer : XXXYZZ

11. If str [] = “Welcome to the world of programming”, then, SUBSTRING


(str,15,5) =
A. world
B. programming
C. welcome
D. None of These
Answer : world

12. strcat () is defined in which of the header files ?


a. ctype.h
b. stdio.h
c. string.h
d. math.h
Answer : string.h

13. A string can be read using which function ?

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


50
CS8251 Programming in C – UNIT II

A. gets()
B. scanf()
C. getchar
D. all of these
Answer : all of these

14. Replace (“XXXYYYZZZ”,”XY”,”AB”) =


a. XXABYYZZZ
b. XABYYYZZZ
c. ABXXXYYYZZ
Answer : XXABYYZZZ

15. The index of U in Oxford University Press is ?


A. 5
B. 6
C. 7
D. 8
Answer : 7
16. s1 = “H1”, s2 = “HELLO”, s3 = “BYE”. How can we concatenate the three
strings ?
A. strcat (s1,s2,s3)
B. strcat (s1(strcat(s2,s3)))
C. strcpy(s1,strcat(s2,s3))
Answer : strcat (s1(strcat(s2,s3)))

17. strlen (“Oxford University Press”) is ?


A. 22
B. 23

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


51
CS8251 Programming in C – UNIT II

C. 24
D. 25
Answer : 23

18. Which function adds a string to the end of another string ?


A. stradd ()
B. strcat ()
C. strtok ()
D. strcpy ()
Answer : strcat ()

19. The tolower() function is defined in ctype.h header file.


A. True
B. False
Answer: True

20. Strings can be read using


A. scanf()
B. gets()
C. getchar()
D. All the above
Answer: All the above

B. Shanmuga Sundari, ASP/CSE, 9632 PET Engineering College, Vallioor


52

You might also like