I B.
SC - 2 Semester (‘C’ Language) UNIT-3
Unit – III
Arrays:
Introduction – Declaration of Arrays – Accessing elements of the Array – Storing Values in
Array – Calculating the length of the Array – Operations on Array – one dimensional array for inter-
function communication – Two dimensional Arrays –Operations on Two Dimensional Arrays - Two
Dimensional Arrays for inter-function communication – Multidimensional Arrays – Sparse Matrices
Strings:
Introduction –Suppressive Input – String Taxonomy – String Operations – Miscellaneous String
and Character functions
Array:
Array a kind of data structure that can store a fixed-size sequential collection of elements of the
same type. A group of related data type items, which share common name. It is a set of homogeneous
data. They can be used to store collection of primitive data types such as int, float, double, char, etc of
any particular type. An array is a variable that can store multiple values. By using the array, we can
access the elements easily. Only a few lines of code are required to access the elements of the array.
Def: Array is a linear data structure which stores collection of homogeneous or similar data type
elements in a continuous memory location with same/single reference variable.
Properties of Array:
The array contains the following properties.
Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.
Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Use of arrays:
1. Storing more than one value at a time under a single name.
2. Reading, processing and displaying the array elements is easy.
3. Some logics can be implemented only through arrays.
Types of arrays:
There are three types ‟ arrays”.
1. One-dimensional array(1-D) 2. Two-dimensional array(2-D) 3. Multi dimensional array
1. One dimensional arrays:
This array consists of only one subscript or index. This type of array is also called single or one
dimensional array.
Syntax:
datatype array-name[size];
Datatype: what kind of values it can store. For example, int, float, char, double.
Name: to identify the array.
Size: the maximum number of values it can store.
Example:
int a[10];
In the above statement array name “a” has 10 integer locations, “a” occupied memory is 20 bytes
(2*10). Organization of the elements in memory: a[0] a[1] ……. a[9]
Aditya Degree College, GWK - By Mohana Roopa 1
I B.SC - 2 Semester (‘C’ Language) UNIT-3
ACCESSING ELEMENTS OF THE ARRAY
To access all the elements of the array, you must use a loop. That is, we can access all the
elements of the array by varying the value of the subscript into the array. But note that the subscript
must be an integral value or an expression that evaluates to an integral value.
Eg:
// Set each element of the array to –1
int i, marks[10];
for(i= 0;i<1 ;i++)
marks[i] = –1;
CALCULATING THE ADDRESS OF ARRAY ELEMENTS
Address of data element,
A[k] = BA(A) + w( k – lower_bound);
Here, ‘A’ is the array
‘k’ is the index of the element of which we have to calculate the address
‘BA’ is the base address of the array A.
‘w’ is the word size of one element in memory.
for example, size of int is 2.
Marks[4] = 1000 + 2(4 – 0)
= 1008
Calculating the Length of an Array
The length of an array is given by the number of elements stored in it. The general formula to calculate
the length of an array is
Length = upper_bound – lower_bound + 1
where “upper_bound “ is the index of the last element and “ lower_bound “ is the index of the first
element in the array.
Example : The memory representation of the array Age[5]
Length = upper_bound – lower_bound + 1
Here, lower_bound = 0, upper_bound = 4
Therefore, length = 4 – 0 + 1 = 5.
STORING VALUES IN ARRAYS:
When we declare an array, we are just allocating space for its elements; no values are stored in
the array. There are three ways to store values in an array. First, to initialize the array elements during
declaration; second, to input values for individual elements from the keyboard; third, to assign values to
individual elements.
Initializing Arrays during Declaration
The elements of an array can be initialized at the time of declaration, just as any other variable.
When an array is initialized, we need to provide a value for every element in the array. Arrays are
initialized by writing,
Aditya Degree College, GWK - By Mohana Roopa 2
I B.SC - 2 Semester (‘C’ Language) UNIT-3
type array_name[size]={list of values};
Eg:
int marks[5]={90, 82, 78, 95, 88};
Inputting Values from the Keyboard
An array can be initialized by inputting values from the keyboard. In this method, a while/do–
while or a for loop is executed to input the value for each element of the array. For example
for(i= 0;i<n ;i++)
scanf("%d", &marks[i]);
we start at the index i at 0 and input the value for the first element of the array. If the array has
10 elements, we must input values for elements whose index varies from 0 to 9.
Assigning Values to Individual Elements
The third way is to assign values to individual elements of the array by using the assignment
operator. Any value that evaluates to the data type as that of the array can be assigned to the individual
array element. A simple assignment statement can be written as :
marks[3] = 100;
Here, 100 is assigned to the fourth element of the array which is specified as marks[3].
OPERATIONS ON ARRAYS
There are a number of operations that can be preformed on arrays. These operations include:
1. Traversing an array
2. Inserting an element in an array
3. Searching an element in an array
4. Deleting an element from an array
5. Merging two arrays
6. Sorting an array in ascending or descending order
1. Traversal/Accessing:
Traversing the array element means accessing each and every element of an array for a specific
purpose. To access all the elements of an array you must use a loop. The subscript must be an integral
value or an expression that evaluates to an integral value.
Eg: //display value of each element in array
int i, a[10];
for(i=0;i<10;i++)
printf(“%d”,a[i]);
2. Insertion:
Insertion an element in an array means adding a new data element in a already existing array.
3. Deletion:
Deleting an element from the array means removing a data elements from already existing array.
4. Merging:
Merging two arrays in a third array means first copying the contents of the first array and then
copying the contents of the second array into the third array. Hence, the merged array contains contents
of first array followed by the contents of the second array.
5. Sorting:
The term sorting means arranging the elements of the array in some relevant order may either be
ascending or descending.
6. Searching the array elements:
Searching means to find whether a particular value is present in the array or not. If the value is
present in the array, then searching is said to be successful and gives the location of that value in the
array. Otherwise searching is said to be unsuccessful.
There are two popular methods for searching the array elements .
They are: 1.Linear search
2. Binary search
Write a program to find the mean of n numbers using arrays.
Aditya Degree College, GWK - By Mohana Roopa 3
I B.SC - 2 Semester (‘C’ Language) UNIT-3
#include <stdio.h>
int main()
{
int i, n, arr[20], sum =0;
float mean = 0.0;
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++)
sum += arr[i];
mean = (float)sum/n;
printf("\n The sum of the array elements = %d", sum);
printf("\n The mean of the array elements = %.2f", mean);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The sum of the array elements = 15
The mean of the array elements = 3.00
Write a program to print the position of the smallest number of n numbers using arrays.
#include <stdio.h>
int main()
{
int i, n, arr[20], small, pos;
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements : ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
small = arr[0]
pos =0;
for(i=1;i<n;i++)
{
if(arr[i]<small)
{
small = arr[i];
pos = i;
}
}
printf("\n The smallest element is : %d", small);
printf("\n The position of the smallest element in the array is : %d", pos);
Aditya Degree College, GWK - By Mohana Roopa 4
I B.SC - 2 Semester (‘C’ Language) UNIT-3
return 0;
}
Output
Enter the number of elements in the array : 5
Enter the elements : 7 6 5 14 3
The smallest element is : 3
The position of the smallest element in the array is : 4
One dimensional array of inter function communication:
Like variables of other data types, we can also pass an array to a function. In some situations,
you may want to pass individual elements of the array; while in other situations, you may want to pass
the entire array.
(a) Passing individual array elements
The individual elements of an array can be passed to a function either by passing
(i) their data values (or) (ii) their address.
(i) passing data values:
The individual elements can be passed in the same manner as we pass variables of any other
data type.
(ii)Passing their addresses:
We can pass the address of an individual array element by preceding the address operator(&) to
the elements indexed reference. We will write &a[3], in the called function the value of the array
element must be accused using the indirection (*)operator.
(b) Passing an entire array to functions:
Passing array elements to a function is similar to passing variables to a function.
2. Two dimensional Arrays
Aditya Degree College, GWK - By Mohana Roopa 5
I B.SC - 2 Semester (‘C’ Language) UNIT-3
C language supports multidimensional arrays also. The simplest form of a multidimensional
array is the two-dimensional array. The two dimensional (2D) array in C programming is also known as
matrix. A matrix can be represented as a table of rows and columns. Both the row's and column's index
begins from 0.
Declaration of 2D array: Two-dimensional arrays are declared as follows,
Syntax:
data-type array-name[row-size][column-size]
Example:
int x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the
array as a table with 3 rows and each row has 4 columns.
Storing elements in an 2D array:
After an array is declared it must be initialized. Otherwise, it will contain garbage value(any
random value). An array can be initialized at either compile time or at runtime.
To store values into an array can be done in two ways:
1. at compile time
2. at run time
1. Compile time array initialization:
Storing values at compile time also known as Initializing. Means giving values to an array at the
time of declaration.
Syntax:
Datarype arrayname[rowsize][columnsize]={list of values}
Eg:
int disp[2][4] = { {10, 11, 12, 13}, {14, 15, 16, 17} }; (OR)
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
Although both the above declarations are valid, I recommend you to use the first method as it is
more readable, because you can visualize the rows and columns of 2d array in this method.
Things that you must consider while initializing a 2D array
We already know, when we initialize a normal array (or you can say one dimensional array)
during declaration, we need not to specify the size of it. However that’s not the case with 2D array, you
must always specify the second dimension even if you are specifying elements during the declaration.
examples
int a[2][2] = {1, 2, 3 ,4 } /* Valid declaration*/
int a[][2] = {1, 2, 3 ,4 } /* Valid declaration*/
int a[][] = {1, 2, 3 ,4 } /* Invalid declaration – you must specify second dimension*/
int a[2][] = {1, 2, 3 ,4 } /* Invalid because of the same reason mentioned above*/
2. Run time array initialization:
How to store user input data into 2D array:
To store the elements entered by user we are using two for loops, one of them is a nested loop.
The outer loop runs from 0 to the (first subscript -1) and the inner for loops runs from 0 to the (second
subscript -1). This way the order in which user enters the elements would be a[0][0], a[0][1], a[0][2]…
so on.
Eg:
Aditya Degree College, GWK - By Mohana Roopa 6
I B.SC - 2 Semester (‘C’ Language) UNIT-3
Printf(“Enter elements into array”);
for(i=0; i<5; i++)
{
for(j=0;j<4;j++)
{
scanf("%d", &abc[i][j]);
}
}
Operations on 2D arrays:
Following operations are performed on 2D arrays.
1)add/sum
2)difference
3)Product
4)Transpose
Transpose: The transpose of mxn matrix A is given as anxm matrix B.
Where Bi,j = Aj,i
Sum : Two matrices that are compatible with each other can be added together there by storing the
result in third matrix.
Ci,j = Ai,j + Bi,j
Difference: Two matrices that are compatible with each other can be subtracted there by storing the
result in the third matrix.
Ci,j = Ai,j – Bi,j
Product: Two matrices can be multiplied with each other if the number of columns in the first matrix
is equal to the number of rows in the second matrix. Therefore, mxn matrix A can be multiplied with a
pxq matrix if n=q elements of matrices can be multiplied by writing.
Ci,j =∑ Ai,kBj,k for k=1 to k<n
Write a program to transpose a 3X3 matrix.
#include <stdio.h>
#include <conio.h>
int main()
{
int i, j, mat[3][3], transposed_mat[3][3];
clrscr();
printf("\n Enter the elements of the matrix ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d", &mat[i][j]);
}
printf("\n The elements of the matrix are ");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("\t %d", mat[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
transposed_mat[i][j] = mat[j][i];
}
printf("\n The elements of the transposed matrix are ");
Aditya Degree College, GWK - By Mohana Roopa 7
I B.SC - 2 Semester (‘C’ Language) UNIT-3
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("\t %d",transposed_ mat[i][j]);
}
return 0;
}
Output
Enter the elements of the matrix
123456789
The elements of the matrix are
123
456
789
The elements of the transposed matrix are
147
258
369
Write a program to multiply two m X n matrices.
#include <stdio.h>
#include <conio.h>
int main()
{
int i, j, k;
int rows1, cols1, rows2, cols2, res_rows, res_cols;
int A[5][5], B[5][5], C[5][5];
clrscr();
printf("\n Enter the number of rows in the first matrix : ");
scanf("%d",&m);
printf("\n Enter the number of columns in the first matrix : ");
scanf("%d",&n);
printf("\n Enter the number of rows in the second matrix : ");
scanf("%d",&p);
printf("\n Enter the number of columns in the second matrix : ");
scanf("%d",&q);
if(n != p)
{
printf("\n The number of columns in the first matrix must be equal
to the number of rows in the second matrix");
getch();
exit();
}
printf("\n Enter the elements of the first matrix ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&A[i][j]);
}
printf("\n Enter the elements of the second matrix ");
for(i=0;i<p;i++)
{
Aditya Degree College, GWK - By Mohana Roopa 8
I B.SC - 2 Semester (‘C’ Language) UNIT-3
for(j=0;j<q;j++)
scanf("%d",&B[i][j]);
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
C[i][j]=0;
for(k=0; k<n;k++)
C[i][j] += A[i][k] * B[k][j];
}
}
printf("\n The elements of the product matrix are ");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<q;j++)
printf(" %d",C[i][j]);
}
return 0;
}
Output
Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix: 2
Enter the number of rows in the second matrix: 2
Enter the number of columns in the second matrix: 2
Enter the elements of the first matrix
1234
Enter the elements of the second matrix
5678
The elements of the product matrix are
19 22
43 50
2-D arrays for inter function communication:
There are three ways of passing a two-dimensional array to a function. First, we can pass
individual elements of the array. This is exactly the same as passing an element of a one-dimensional
array. Second, we can pass a single row of the two-dimensional array. This is equivalent to passing the
entire one-dimensional array to a function that has already been discussed in a previous section. Third,
we can pass the entire two-dimensional array to the function.
Passing a Row
A row of a two-dimensional array can be passed by indexing the array name with the row
number.
Aditya Degree College, GWK - By Mohana Roopa 9
I B.SC - 2 Semester (‘C’ Language) UNIT-3
Passing the Entire 2D Array
To pass a two-dimensional array to a function, we use the array name as the actual parameter
(the way we did in case of a 1D array). However, the parameter in the called function must indicate
that the array has two dimensions.
Eg:
Write a program to fill a square matrix with value zero on the diagonals, 1 on the upper right triangle,
and –1 on the lower left triangle.
#include <stdio.h>
#include <conio.h>
void read_matrix(int mat[5][5], int);
void display_matrix(int mat[5][5], int);
int main()
{
int row;
int mat1[5][5];
clrscr();
printf("\n Enter the number of rows and columns of the matrix:");
scanf("%d", &row);
read_matrix(mat1, row);
display_matrix(mat1, row);
getch();
return 0;
}
void read_matrix(int mat[5][5], int r)
{
int i, j;
for(i=0; i<r; i++)
{
for(j=0; j<r; j++)
{
if(i==j)
mat[i][j] = 0;
else if(i>j)
mat[i][j] = –1;
else
mat[i][j] = 1;
}
}
}
void display_matrix(int mat[5][5], int r)
{
int i, j;
for(i=0; i<r; i++)
{
printf("\n");
for(j=0; j<r; j++)
Aditya Degree College, GWK - By Mohana Roopa 10
I B.SC - 2 Semester (‘C’ Language) UNIT-3
printf("\t %d", mat[i][j]);
}
}
Output
Enter the number of rows and columns of the matrix: 2
01
–1 0
SPARSE MATRICES
Sparse matrix is a matrix that has large number of elements with a zero value. In order to
efficiently utilize the memory, specialized algorithms and data structures that take advantage of the
sparse structure should be used. If we apply the operations using standard matrix structures and
algorithms to sparse matrices, then the execution will slow down and the matrix will consume large
amount of memory. Sparse data can be easily compressed, which in turn can significantly reduce
memory usage.
Sparse matrix are of three types.
1. Lower Triangular matrix
2. Upper Triangular matrix
3. Tri-diagonal matrix
(a) Lower Triangular matrix:
Lower triangular matrix is a square matrix if all elements above
the main diagonal have a value zero. So, this type of matrix is called as
Lower Triangular matrix.
All the elements with non –zero value appear below the main
diagonal.
The mapping between an two dimensional matrix[2D] and one
dimensional array [1D] array can be in 2 ways.
Row wise mapping [ 1 5 3 2 7 -1 3 1 4 2 -9 2 -8 1 7 ]
Column wise mapping [ 1 5 2 3 – 9 3 7 1 2 -1 4 -8 2 1 7]
(b)Upper Triangular matrix:
Upper Triangular matrix is a square matrix if all the elements
below the main diagonal have a value zero. So this type of matrix is
called Upper Triangular matrix.
All the elements with non –zero value appear above the main
diagonal.
The mapping between an two dimensional matrix[2D] and one
dimensional array [1D] array can be in 2 ways.
Row wise mapping [1 2 3 4 5 3 6 7 8 -1 9 1 9 2 7 ]
Column wise mapping [1 2 3 3 6 -1 4 7 9 9 5 8 1 2 7 ]
(c)Tri-diagonal matrix:
Tri-diagonal matrix is square matrix if all elements with non-zero
value can appear on the main diagonal or immediately above or below
diagonal is known as Tri-diagonal matrix.
Here all the elements with non zero values on the main diagonal and also
below and above diagonal.
Row-wise mapping : [ 4 1 5 1 2 9 3 1 4 2 2 5 1 9 8 7]
Column- wise mapping: [4 5 1 1 9 2 3 4 1 2 5 2 1 8 9 7]
Aditya Degree College, GWK - By Mohana Roopa 11
I B.SC - 2 Semester (‘C’ Language) UNIT-3
Strings:
Computers are widely used for word processing applications such as creating, inserting,
updating, and modifying textual data. Besides this, we need to search for a particular pattern within a
text, delete it, or replace it with another pattern. So, there is a lot that we as users do to manipulate the
textual data.
In C, a string is a null-terminated character array. This means that after the last character, a
null character ('\0') is stored to signify the end of the character array. For example, if we write
char str[] = "HELLO";
then we are declaring an array that has five characters, namely, H, E, L, L, and O. Apart from
these characters, a null character ('\0') is stored at the end of the string. So, the internal representation of
the string becomes HELLO'\0'. To store a string of length 5, we need 5 + 1 locations (1 extra for the
null character). The name of the character array (or the string) is a pointer to the beginning of the string.
Reading Strings
If we declare a string by writing
char str[100];
Then str can be read by the user in three ways:
1. using scanf function,
2. using gets() function, and
3. using getchar(),getch()or getche() function repeatedly.
1. using scanf function :
Strings can be read using scanf() by writing
scanf("%s", str);
Although the syntax of using scanf() function is well known and easy to use, the main pitfall of
using this function is that the function terminates as soon as it finds a blank space. Unlike int, float, and
char values, %s format does not require the ampersand(&) before the variable str.
2. using gets() function :
The next method of reading a string is by using the “gets()” function. The string can be read by
writing
gets(str);
gets() is a simple function that overcomes the drawbacks of the scanf() function. The gets()
function takes an entire line of string. The string inputted using gets() is automatically terminated with a
null character.
3. using getchar() :
Strings can also be read by calling the getchar() function repeatedly to read a sequence of
single characters (unless a terminating character is entered) and simultaneously storing it in a
character array as shown below.
i=0; ch = getchar;// Get a character
while(ch != '*')
{
str[i] = ch;// Store the read character in str
i++;
ch = getchar();// Get another character
}
str[i] = '\0';// Terminate str with null character
Aditya Degree College, GWK - By Mohana Roopa 12
I B.SC - 2 Semester (‘C’ Language) UNIT-3
Writing Strings
Strings can be displayed on the screen using the following three ways:
1. using printf() function,
2. using puts() function, and
3. using putchar() function repeatedly.
1. using printf() function :
Strings can be displayed using printf() by writing, We use the format specifier %s to output a
string.
printf("%s", str);
printf() prints the string until the first space.
2. using puts() function :
The next method of writing a string is by using puts() function. A string can be displayed by
writing
puts(str);
puts() is a simple function that overcomes the drawbacks of the printf() function.We can print an
entire line of text using puts().
3. using putchar() function :
Strings can also be written by calling the putchar() function repeatedly to print a sequence of
single characters.
i=0;
while(str[i] != '\0')
{
putchar(str[i]);// Print the character on the screen
i++;
}
ARRAYS OF STRINGS
suppose that there are 20 students in a class and we need a string that stores the names of all the
20 students. How can this be done? Here, we need a string of strings or an array of strings. Such an
array of strings would store 20 individual strings.
An array of strings is declared as
char names[20][30];
Here, the first index will specify how many strings are needed and the second index will specify
the length of every individual string. So here, we will allocate space for 20 names where each name can
be a maximum 30 characters long.
Let us see the memory representation of an array of strings. If we have an array declared as
char name[5][10] = {"Ram", "Mohan", "Shyam", "Hari", "Gopal"};
Then in the memory, the array will be stored as
Write a program to sort the names of students.
#include <string.h>
int main()
{
char names[5][10], temp[10];
int i, n, j;
Aditya Degree College, GWK - By Mohana Roopa 13
I B.SC - 2 Semester (‘C’ Language) UNIT-3
printf("\n Enter the number of students : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the name of student %d : ", i+1);
gets(names[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n–i–1;j++)
{
if(strcmp(names[j], names[j+1])>0)
{
strcpy(temp, names[j]);
strcpy(names[j], names[j+1]);
strcpy(names[j+1], temp);
}
}
}
printf("\n Names of the students in alphabetical order are : ");
for(i=0;i<n;i++)
puts(names[i]);
getch();
return 0;
}
Output
Enter the number of students : 3
Enter the name of student 1 : Goransh
Enter the name of student 2 : Aditya
Enter the name of student 3 : Sarthak
Names of the students in alphabetical order are : Aditya Goransh Sarthak
POINTERS AND STRINGS
we are creating a string str using char character array of size 6.
char str[6] = "Hello";
The variable name of the string str holds the address of the first element of the array i.e., it
points at the starting memory address. So, we can create a character pointer ptr and store the address of
the string str variable in it. This way, ptr will point at the string str.
In the following code we are assigning the address of the string str to the pointer ptr.
char *ptr = str;
We can represent the character pointer variable ptr as follows:
The pointer variable ptr is allocated memory address 8000 and it holds the address of the string
Aditya Degree College, GWK - By Mohana Roopa 14
I B.SC - 2 Semester (‘C’ Language) UNIT-3
variable str i.e., 1000.
Accessing string via pointer
To access and print the elements of the string we can use a loop and check for the \0 null
character. In the following example we are using while loop to print the characters of the string
variable str.
#include <stdio.h>
int main(void) {
char str[6] = "Hello";
char *ptr = str;
while(*ptr != '\0') {
printf("%c", *ptr);
ptr++;
}
return 0;
}
String handling functions in ‘C’:
You need to often manipulate strings according to the need of a problem. Most, if not all, of the
time string manipulation can be done manually but, this makes programming complex and large.
To solve this, C supports a large number of string handling functions in the standard
library "string.h".
Few commonly used string handling functions are discussed below:
Functio
n Work of Function
strlen() computes string's length
strcpy() copies a string to another
strcat() concatenates(joins) two strings
strcmp() compares two strings
strlwr() converts string to lowercase
strupr() converts string to uppercase
strlen() function
strlen( ) function in C gives the length of the given string. Syntax for strlen( ) function is given
below.
int strlen ( const char * str );
strlen( ) function counts the number of characters in a given string and returns the integer value.
It stops counting the character when null character is found. Because, null character indicates
the end of the string in C.
Example:
#include <string.h>
int main( )
{
int len;
char array[25]="Aditya Degree College" ;
len = strlen(array) ;
printf ( "\string length = %d \n" , len ) ;
return 0;
}
OUTPUT:
Aditya Degree College, GWK - By Mohana Roopa 15
I B.SC - 2 Semester (‘C’ Language) UNIT-3
string length = 21
strcmp() function
strcmp( ) function in C compares two given strings and returns zero if they are same.
If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0
value. Syntax for strcmp( ) function is given below.
int strcmp ( const char * str1, const char * str2 );
strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
Eg:
#include <string.h>
int main()
{
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
Output
strcmp(str1, str2) = 32
strcmp(str1, str3) = 0
strcat() function
strcat( ) function in C language concatenates two given strings. It concatenates source string at
the end of destination string. Syntax for strcat( ) function is given below.
char * strcat ( char * destination, const char * source );
Example:
strcat ( str2, str1 ); – str1 is concatenated at the end of str2.
strcat ( str1, str2 ); – str2 is concatenated at the end of str1.
As you know, each string in C is ended up with null character (‘\0’).
In strcat( ) operation, null character of destination string is overwritten by source string’s first
character and null character is added at the end of new destination string which is created after
strcat( ) operation.
Eg:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "This is ", str2[] = "a C program";
strcat(str1,str2);
puts(str1);
puts(str2);
return 0;
}
Output
This is a C Program
a C Program
strrev() function
strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is given
below.
char *strrev(char *string);
Aditya Degree College, GWK - By Mohana Roopa 16
I B.SC - 2 Semester (‘C’ Language) UNIT-3
strrev( ) function is non standard function which may not available in standard library in C.
Eg:
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
return 0;
}
OUTPUT:
String before strrev( ) : Hello
String after strrev( ) : olleH
strlwr() function
strlwr( ) function converts a given string into lowercase. Syntax for strlwr( ) function is given
below.
char *strlwr(char *string);
strlwr( ) function is non standard function which may not available in standard library in C.
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%s\n",strlwr (str));
return 0;
}
OUTPUT:
modify this string to lower
strupr() function
strupr( ) function converts a given string into uppercase. Syntax for strupr( ) function is given
below.
char *strupr(char *string);
strupr( ) function is non standard function which may not available in standard library in C.
Eg:
#include<string.h>
int main()
{
char str[ ] = "Modify This String To Upper";
printf("%s\n",strupr(str));
return 0;
}
OUTPUT:
MODIFY THIS STRING TO UPPER
strcpy() function
strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is
given below.
char * strcpy ( char * destination, const char * source );
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
Aditya Degree College, GWK - By Mohana Roopa 17
I B.SC - 2 Semester (‘C’ Language) UNIT-3
If destination string length is less than source string, entire source string value won’t be copied
into destination string.
For example, consider destination string length is 20 and source string length is 30. Then, only
20 characters from source string will be copied into destination string and remaining 10
characters won’t be copied and will be truncated.
Eg:
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
OUTPUT:
source string = fresh2refresh
target string after strcpy( ) = fresh2refresh
LIST OF PREDEFINED CHARACTER FUNCTIONS IN C:
“ctype.h” header file support all the below functions in C language.
Functions Description
isalpha() checks whether character is alphabetic
isdigit() checks whether character is digit
Checks whether character is
isalnum() alphanumeric
isspace() Checks whether character is space
islower() Checks whether character is lower case
isupper() Checks whether character is upper case
Checks whether character is
isxdigit() hexadecimal
Checks whether character is a control
iscntrl() character
Checks whether character is a printable
isprint() character
Checks whether character is a
ispunct() punctuation
Checks whether character is a
isgraph() graphical character
Checks whether character is alphabetic
tolower() & converts to lower case
Checks whether character is alphabetic
toupper() & converts to upper case
Aditya Degree College, GWK - By Mohana Roopa 18
I B.SC - 2 Semester (‘C’ Language) UNIT-3
Reading Single Character from keyboard:
getchar():
getchar is a function in C programming language that reads a single character from the standard
input stream stdin, regardless of what it is, and returns it to the program. It is specified in ANSI-C and is the
most basic input function in C. It is included in the stdio.h header file.
The getchar function syntax is:
int getchar(void);
Eg:
#include <stdio.h>
int main()
{
char str[100];
int i=0,j=0;
printf("Enter the string into the file\n");
while((str[i]=getchar())!='\n')
i++;
str[i]='\0';
printf("\nThe string is - ");
while(str[j]!='\0')
{
putchar(str[j]);
j++;
}
}
getc():
It reads a single character from a given input stream and returns the corresponding integer value
(typically ASCII value of read character) on success. It returns EOF on failure.
Syntax:
int getc(FILE *stream);
Eg:
#include <stdio.h>
int main()
{
printf("%c", getc(stdin));
return(0);
}
Input: g (press enter key)
Output: g
getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly used by
MS-DOS compilers like Turbo C. Like above functions, it reads also a single character from keyboard.
But it does not use any buffer, so the entered character is immediately returned without waiting for the
enter key.
Syntax:
int getch();
Eg:
#include <stdio.h>
#include <conio.h>
int main()
{
printf("%c", getch());
Aditya Degree College, GWK - By Mohana Roopa 19
I B.SC - 2 Semester (‘C’ Language) UNIT-3
}
Input: g (Without enter key)
Output: Program terminates immediately.
But when you use DOS shell in Turbo C,
it shows a single g, i.e., 'g'
getche():
Like getch(), this is also a non-standard function present in conio.h. It reads a single character
from the keyboard and displays immediately on output screen without waiting for enter key.
Syntax:
int getche(void);
Example:
#include <stdio.h>
#include <conio.h>
// Example for getche() in C
int main()
{
printf("%c", getche());
return 0;
}
Print a Single Character:
Putchar():
The putchar(int char) method in C is used to write a character, of unsigned char type, to stdout.
This character is passed as the parameter to this method. This function returns the character written on
the stdout as an unsigned char. It also returns EOF when some error occurs.
Syntax:
int putchar(int char);
Eg:
#include <stdio.h>
int main()
{
char ch = 'G';
putchar(ch);
}
Output:
G
putc():
putc() function is C library function, and it's used to write a character to the file. This function is
used for writing a single character in a stream along with that it moves forward the indicator's position.
Syntax:
int putc( int c, FILE * stream );
Eg:
int main (void)
{
FILE * fileName;
char ch;
fileName = fopen("anything.txt","wt");
for (ch = 'D' ; ch <= 'S' ; ch++) {
putc (ch , fileName);
}
fclose (fileName);
Aditya Degree College, GWK - By Mohana Roopa 20
I B.SC - 2 Semester (‘C’ Language) UNIT-3
}
Aditya Degree College, GWK - By Mohana Roopa 21