Unit-3: Arrays
Unit-3: Arrays
The C language provides a capability that enables the user to define a set of ordered data
items known as an array.
Suppose we had a set of grades that we wished to read into the computer and suppose
we wished to perform some operations on these grades, we will quickly realize that we
cannot perform such an operation until each and every grade has been entered since it
would be quite a tedious task to declare each and every student grade as a variable
especially since there may be a very large number.
In C we can define a variable called grade, which represents not a single value of grade
but a entire set of grades. Each element of the set can then be referenced by means of a
number called as index number or subscript.
Declaration of arrays
Like any other variable arrays must be declared before they are used. The general form
of declaration is:
type variable-name[50];
The type specifies the type of the elements that will be contained in the array, such as int
float or char and the size indicates the maximum number of elements that can be stored
inside the array for ex:
float height[50];
The statement assigns the value stored in the 50th index of the array to the variable g.
More generally if i is declared to be an integer variable, then the statement
g=grades[i]; will take the value contained in the element number i of the grades array to
assign it to g.
So, if i were equal to 7 when the above statement is executed, then the value of grades
[7] would get assigned to g. A value stored into an element in the array simply by
specifying the array element on the left-hand side of the equals sign. In the statement
As individual array element can be used anywhere that a normal variable with a statement
such as
grades [100]=95;
The value 95 is stored into the element number 100 of the grades array. The ability to
represent a collection of related data items by a single array enables us to develop
concise and efficient programs. For example we can very easily sequence through the
elements in the array by varying the value of the variable that is used as a subscript into
the array. So the for loop
Will sequence through the first 100 elements of the array grades (elements 0 to 99) and
will add the values of each grade into sum. When the for loop is finished, the variable sum
will then contain the total of first 100 values of the grades array (Assuming sum were set
to zero before the loop was entered).
Just as variables arrays must also be declared before they are used. The declaration of
an array involves the type of the element that will be contained in the array such as int,
float, char as well as maximum number of elements that will be stored inside the array.
The C system needs this latter information in order to determine how much memory space
to reserve for the particular array.
The declaration int values[10]; would reserve enough space for an array called values
that could hold up to 10 integers. Refer to the below given picture to conceptualize the
reserved storage space.
values[0]
values[1]
values[2]
values[3]
values[4]
values[5]
values[6]
values[7]
values[8]
values[9]
Initialization of arrays
We can initialize the elements in the array in the same way as the ordinary variables when
they are declared. The general form of initialization off arrays is:
The values in the list care separated by commas, for example the statement
int number[3]={0,0,0};
Will declare the array size as a array of size 3 and will assign zero to each element if the
number of values in the list is less than the number of elements, then only that many
elements are initialized. The remaining elements will be set to zero automatically.
In the declaration of an array the size may be omitted, in such cases the compiler
allocates enough space for all initialized elements. For example, the statement
int counter[]={1,1,1,1};
Will declare the array to contain four elements with initial values 1. This approach works
fine as long as we initialize every element in the array.
{
int a[50],n,count_neg=0,count_pos=0,i;
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);
if(a[i] < 0)
count_neg++;
else
count_pos++;
}
Multi-dimensional Arrays
Often there is a need to store and manipulate two-dimensional data structure such as
matrices & tables. Here the array has two subscripts. One subscript denotes the row &
the other the column.
data-type array-name[row-size][column-size];
int m[10][20];
A 2-dimensional array marks [4][3] is shown below figure. The first element is given by
marks [0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so on.
marks
[0][0] Marks [0][1] Marks [0][2]
35.5 40.5 45.5
marks
[1][0] Marks [1][1] Marks [1][2]
50.5 55.5 60.5
marks
[2][0] Marks [2][1] Marks [2][2]
marks
[3][0] Marks [3][1] Marks [3][2]
Like the one-dimension arrays, two-dimension arrays may be initialized by following their
declaration with a list of initial values enclosed in braces
Initializes the elements of first row to zero and second row to 1. The initialization is done
row by row. The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}}
int survey[3][5][12];
float table[5][4][5][3];
‘survey’ is a 3-dimensional array declared to contain 180 integer elements. Similarly, table
is a four-dimensional array containing 300 elements of floating-point type.
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Assignment:
1. WAP in C to add two matrices and store the results in the 3rd matrix.
3. Write a C program to find accept a matrix of order M x N and find the sum of both
the main diagonal elements.
4. Write a C program to accept a matrix of order M x N and find the sum of each row
and each column of a matrix.
6. Write a C program to read N integers into an array A and to (a) find the sum of
negative numbers, (b) find the sum of positive numbers and (c) find the average of
all input numbers. Output the various results computed with proper headings.
String Concepts
Memory devices (or storage devices) are collection of memory cells. Each memory
cell can store one bit which is a binary value (0 or 1). Human understandable Information
or data can be represented using the combination of 0s and 1s. The 8 memory cells are
treated as one register which can store 8 bits of binary information. Group of 8 bits are
one byte. Usually computer uses one byte to represent one character. In the memory
each location has some address as shown below.
Memory
Data stored in each location
Address location
: :
: :
630051 W
630052 I
630053 N
630054 D
630055 O
630056 W
630057 S
630058 ‘\0’
: :
: :
Different memory types are RAM, ROM etc. Each memory location in the RAM or
ROM has unique address starting from 0 to MAX. The temporary programs like C are
stored in RAM. The data, programs, or code are stored in RAM memory.
In the above figure the data is WINDOWS. The data stored in the memory location
starting from the address 630051 to 630057 as shown above. Each memory location is
storing one character and each memory location has a unique address.
In a program, we use variables to store data. Based on the data type, memory is
allocated for a variable to data storage. C has different types of data types. They are
integer, float, and char, etc.
When a variable is of integer it needs 2 bytes for storage. When a variable is char
it needs 1 byte. Each variable contains identifier (the name of a variable), address of the
variable and data. The data may be a number, real number (float) or character data. We
store this data into a variable or memory location.
The variable name is NUM, the data type is integer type, which occupies 2 bytes.
The memory allocated is 53002 & 53003. But for ease it is shown only one memory
location.
The variable name is salary which is of float data type which occupies 4 bytes of
memory. The memory locations are 53321, 53322, 53323, and 53324. But for ease it is
shown with start address.
The variable name is ch which is of character data type which occupies only one
byte. The memory location is 54001. The data stored is ‘A’.
Memory Variable
name
Address data
location
630051 W Sw
630052 I
630053 N
630054 D
630055 O
630056 W
630057 S
630058 ‘\0’
Similarly, in the above figure the variable is sw, the data is “WINDOWS” and the
memory location is 630051.
The memory allocated for an integer, float, and char is always constant. But the
length of the data for string variable varies.
Based on the length of a string, they are of two types, namely, fixed length and variable
length.
string
Fixed- Variable
length length
Length
delimited
controlled
C strings
Fixed-length strings:
The string is a constant data which is stored in a variable. The fixed-length string
by name means the length of the string is fixed. So, first thing is to be decided the length
of a variable. We can declare a string with fixed length as shown below.
The above declaration means that we are declaring a variable with a name Ename.
Ename is a variable which stores array of characters. 7 memory locations are allocated
for Ename. The length of the data that it can store should be less than 7 characters. At
the end of the data one byte is allocated to indicate the end of the string. The end of the
string is allocated by null (\0).
Memory Variable
data name
Address
location
630151 K Ename
630152 U
630153 M
A White
630154
space
630155 R
630156 ‘‘
630157 ‘\0’
1) If the length of a variable is declared too small, then we can’t store all the data.
For example, in the above the variable Ename can store any string which contains less
than 7 characters. So, we can store a data string whose character length should be less
than 7. If we try to store the data whose length is greater than 7, then the program may
raise runtime errors.
2) If we declare the length of the string is too big, and if the data to be stored is small.
Then we waste memory.
For example, “KUMAR” is a string which occupies only 5 bytes. After storing the data into
a variable, the remaining empty bytes are filled with white spaces. Here in the above
example it is only one white space waste. These white spaces are waste of memory. In
some cases, these white spaces may be in 100 bytes. The white spaces are treated as
non-data characters. They distinguish between the characters actual data and non-data
characters.
Variable-Length Strings:
Variable-length strings can overcome these two dis-advantages that exist in the
fixed-length strings. Here we can expand and contract to provide correct space to the
data.
To store a person’s name which contains only one letter, we provide only enough
storage for one character. To store a person’s name that consists of only 30 characters,
that structure would be expanded to provide storage for 30 characters.
The end of the data should be indicated with some delimiter. Two common
techniques are to indicate the length of the strings. They are to use length-controlled
strings and delimited strings.
Length-controlled strings
9 C o n f u c i u s
In the above figure the string data is “Confucius” and the length of the data is 9. The count
is stored in the start location of the string.
Delimited Strings
In Delimited Strings no count is used instead they use Delimited Strings. The
delimiter indicates the end of the strings. In script also, every sentence is ended by dot
which is known as delimiter which indicates the end of the sentence. The other different
types of delimiters are commas, semicolons, colon, and dashes etc.
From the above said delimiters, if delimiter (.) is used as the end of a string in the
programming, then those delimiters cannot be used as data characters in between the
string which they may create confusion as shown below.
G . K . T o w e r s .
In the above figure the dot (.) is used as delimiter. We want to write G.K.Towers as one
string which is the address. But instead of one string it treats as 3 different strings
1) G
2) K
3) Towers.
The C uses the ASCII null character (\0), which is the first character in the ASCII
sequence. The Delimited string is shown below. This delimited string technique used by
C as shown in below figure.
delimiter
B O O L E \0
C Strings
Storing strings:
H E L L O \0
The above figure explains that a string “Hello” and a delimiter ‘\0’ are stored in memory.
Therefore, to store any string in a memory the string along with a delimiter is stored.
To store a single character as a char data type we need only one byte. But to store
the single character as string data type, we need two bytes. One is for the character and
other is for delimiter which is shown below.
String
Char data type
Datatype
Char String
‘H’ “H”
H H \0
In C a character is enclosed between single quotes and string is enclosed between double
quotes. In the above figure to store a character ‘H’ we need only one byte. But to store
as string we need two bytes.
The empty string needs only one delimiter which is shown below.
“”
(Empty
string)
\0
If the first location contains null character then such a string is treated as null.
Data types
int I;
float f;
char c;
char S[4];
int, float and char are different data types. i, f & c are variables. The space allocated
for each variable varies. For int data type the space is allocated is 2 bytes, for float it is 4
and for char it is only one byte. The string S is not a data type but a data structure. Here
the space allocated for a string is 4 characters. This implementation is a logical but not
physical.
Take an example
S =”A”
S
A ‘\0’ ? ?
To store a string “A”, we need two bytes.
S =”but”
S
B u t ‘\0’
We need four bytes to store the string “but”.
So, the physical structure is changing. Therefore, to identify this physical structure we use
logical end of the data.
If the data length is fixed then the count is same. Therefore, we don’t need the string data
structure to store the count with the string. Such data can be stored easily and the end of
the data is always the last element in the array.
If the data length is variable we need some way to determine the end of the data.
The null character is used to determine the end of the string. It is the sentinel used by
the standard string functions.
Difference between strings and Character Arrays:
1 The string is terminated by null 1 The end of the array is always the last
character. element of the array.
2 The string has null character. 2 There is no null character in the array
of characters.
3 The string has end of string. 3 Last character is the end of the string
String array
H e L L O \0 H e l l 0
No end of string
Because the strings are variable-length structures, this property makes the string
to change their length. We must provide enough room for the maximum-length string we
will have to store, plus one for delimiter.
Take an example
char str[11]; G o o d D a y \0 ? ?
String Literals
“C is a high-level language”
“Hello”
“abcd”
The above string literals are examples of string constants which can be used in a program.
str1
C i s a h i g h - l e v e l l a n g u a g e \0
Null string
Then C allocates memory for the string literal with the null-delimited string as
shown above. A contiguous memory location is allocated. Characters in the string are
stored contiguously. The address of the first character of the string is the string address
which is stored in the string variable str1. End of the string is terminated by null character
(\0).
To store as a character literal, we use single quote marks. For example ‘a’
To store it as a string literal, we use double quote marks. For example, “a”
Even though, the difference when we code the literal is only a shift key operation
on keyboards. The single quote (‘) and double quote (“) keys, both are positioned on the
same key. To enter single quotes, we use Key board key ‘directly and to enter double
quotes shift + “.
Character literal is stored in a single location that is one byte. To store the same
literal as string literal we need two bytes to fit two literals. The two literals are one is
character and the null delimiter.
Data manipulation also has difference. For example, moving a character from one
location to another requires only an assignment. Moving a string requires a function call.
Strings Characters
“a” ‘a’
A string literal is stored in memory. Just like any object stored in memory, it has an
address. We use pointers to refer to a string literal.
Declaring strings: like int, float & char C does not have data type String. Therefore, we
use other available structures. Since strings are sequence of characters. It is only
procedure to store string variables is the character array.
Declaration means allocate the memory. Declaration is automatic process so no
involvement of a programmer or user.
To store a string, we must provide sufficient room for the data and the delimiter.
Therefore, the storage structure size must be one byte larger than the maximum data
size. Therefore, a string which contains eight characters, including its delimiter needs 9
bytes to be allocated.
The above string declaration defines only memory for a string when it is declared.
Contiguous memory locations are allocated in local memory area. Only memory is
allocated. No, data exists in the memory.
Str
Fixed memory locations allocated. The name of the string is a pointer location. For
future characters also, memory is allocated.
In string pointer declaration, it allocates two bytes to store the address of a string. For
example
The second case allocates memory for a pointer variable. That is only 2 bytes are
allocated for a pointer variable to store the starting address of a string as shown above.
However, no memory is allocated for the string data itself. Any attempt to use the string
before memory the allocation of memory is a logic error which may destroy the memory
contents and may causes our program to fail.
Declaration of a string pointer does not mean that the allocation of memory for a
string. In declaration two bytes are allocated which can store the address. Later after
memory is allocated for the data, the address is stored into the two bytes address as
shown above.
Initializing Strings:
To store a string constant “Good Day” in a string variable str in C is coded as shown
below.
The above statement is also known as assigning “Good Day” to string str.
In the above statement, month does not contain any size but except empty braces. So,
size will be decided by the compiler based on the string constant which is at the right side.
The compiler will create an array of 8 bytes and initialize it with String constant January
which contains 7 bytes and plus one byte for a null character is shown below.
String
8 Bytes are allocated for each character in the array
name
1 2 3 4 5 6 7 8
month J a n u a r Y \0
But after few lines if you want to store a string constant “December” would overrun
the array size and may destroy the contents in the next memory locations. Because
December contains 8 bytes and plus one null character to represent the end of the
character. Totally it takes 9 bytes to store but string variable month can support data
which is up to 8 bytes only. This may override the data next to it which creates malfunction
of the program. So, enough space should be allocated for a string variable that can be
able to store longest String value in the program.
“Good Day” is a string literal or string constant is stored in the string pointer variable pstr.
In the above case two bytes will be allocated for a pointer variable will be created for pstr.
The string “Good Day” is stored in somewhere in memory and the address is stored in
the pointer pstr.
“Good
Day”
1 2 3 4 5 6 7 8 9
pstr G o o d D a y \0
Initializing a string as an array of characters:
In this method also memory can be allocated for the string but this method is
tedious to code.
The procedure is shown below and the end of the string which is null should be shown in
initializing.
“Good
Day”
1 2 3 4 5 6 7 8 9
str G o o d D a y \0
Each character should be enclosed between single quotes and at the end null
character should also be enclosed between the single quotes. All this array of characters
should be enclosed between curly braces as shown above.
In C, the expression can be either rvalue or lvalue. Take for example an assignment
operator
K = 5 + 8;
The above expression uses assignment operator and two operands. lvalue is an
expression k which is at the left side of the assignment operator and rvalue is an
expression 5 + 8 which is at the right side of the assignment operator.
lvalue which is k can be modified. Lvalue is an expression must be used whenever
the object is receiving or storing a value. Here K is receiving a value. The following are
lvalue expression:
The lvalue can be modified which is at the right side of the assignment operator.
We cannot change rvalue expressions; usually they are at the right side of the
assignment operator. The above expression values cannot be modified rather they give
some value after evaluation.
Strings when used assignment operator as shown below. First line is initialization;
the second line is declaring a string variable and the third line is trying to copy the contents
of one string to another string.
char str2[6];
Since the string is an array of characters. The names of the strings are str1 & str2
which are pointer constants. In the third line we want to copy the contents of str1 and
store them into str2. But str1 and str2 are pointer constants. Pointer constants contain the
addresses of strings which cannot be modified. As a pointer constant, it is a rvalue and
therefore cannot be used as the left operand of the assignment operator.
Program: Sample program to print the string by using different formats of initialization of
array.
Line C Program
no
1 #include <stdio.h>
2 #include<conio.h>
3 void main(){
4 char arr[9] = { ‘W’, ‘E’, ‘L’, ‘ ’, ‘C’, ‘O’, ‘M’, ‘E’, ‘\0’};
6 char arr2[9] = { {‘W’}, {‘E’}, {‘L’}, {‘ ‘}, {‘C’}, {‘O’}, {‘M’}, {‘E’}, {‘\0’};
7 clrscr();
11 }
Output:
Array = WELCOME
Array1 = WELCOME
Array2 = WELCOME
Code lines 4, 5 & 6 are initialization of string variables arr, arr1 & arr2. The methods
of initializing a string are different but the operation is same. In the first method we are
trying to store the character array into a variable arr. In the second method we are storing
a string “WELCOME” into string variable arr1. In the third method is also a character array
is stored into string variable arr2.
The last three print lines are printing the strings in the 3 different arrays.
strlen( ) function : This function counts the number of characters in a given string.
Below is a sample program to count the number of characters in a given string. gets
function used read a string from keyboard and store them into the string variable which is
enclosed between braces.
#include <stdio.h>
#include<string.h>
void main()
{
char text [20];
int len;
clrscr ();
printf(“Type Text Below \n”);
gets(text);
len = strlen(text);
printf(“length of string = %d”, len);
}
Output:
Length of string = 5
strcpy( ) function: This function copies the contents of one string variable to another
string variable. S1 is source string we are trying to copy the contents to destination string
s2.
Sample program to copy contents of one string to another string by using strcpy(). Here
in the below program
main()
{
char ori[20], dup[20];
clrscr();
printf(“Enter your name:”);
gets(ori);
strcpy(dup, ori);
printf(“original string: %s”,ori);
printf(“\n Duplicate string: %s”,dup);
}
Output:
Enter your name: Kumar
Original string: Kumar
Duplicate string: Kumer
strncpy copies specified length of characters from source to destination string where as
strcpy function copies the source string to destination string.
Sample program to copy the n characters of string to another string using strncmp ()
function.
#include< stdio.h>
main(){
char str[10],tar[10];
int n;
clrscr();
printf(“Enter the 1st string”);
gets(sr);
printf(“Enter the No. of characters to be copied”);
Scanf(“%d”, n);
stricmp(sr, tar , n);
puts(“Source string:”);
puts (str);
puts(“target string:”);
puts(tar);
}
Output:
Enter the 1st string computer
Enter the No. of characters to be copied: 4
Source string: Computer
Target string: Comp
Explanation: The program wants the source string and no. of characters to be copied
here it is 4. Then using strncpy function the program copies the first 4 characters here it
is “COMP” is copied to target string.
stricmp() function: This function compares the two strings and it ignore the case. The
characters of the string may be in lowercase or upper case. The function does not
discriminate between them, i.e., this function compares two strings without case. If the
strings are same, it returns to zero otherwise non-zero value.
#include< stdio.h>
main()
{
char str[10],tar[10];
int diff;
printf(“Enter the 1st string”);
gets(sr);
printf(“Enter the 2nd string”);
gets(tar);
diff = stricmp(sr, tar);
if(diff = = 0)
puts (“Identical strings”);
else
puts(“Not identical”);
}
Output:
Identical strings
Explanation: Here two strings are same, but used different cases. Even though, the
program displays identical strings. So, function does not discriminate between strings.
Output2:
Not Identical
strcmp() function: It performs the same task as stricmp() function. The strcmp() function
discriminates between small and capital letters.
#include< stdio.h>
main()
{
char str[10],tar[10];
int diff;
clrscr();
printf(“Enter the 1st string”);
gets(sr);
printf(“Enter the 2nd string”);
gets(tar);
diff = stricmp(sr, tar);
if(diff = = 0)
puts (“Identical strings”);
else
puts(“Not identical”);
}
Output:
Enter the 1st string computer
Enter the 2nd string Computer
Not Identical
Output2:
Enter the 1st string computer
Enter the 2nd string computer
Identical strings
strncmp() function: It compares the two strings up to certain specified length. The format
of this function is strncmp(source, target, argument);
Sample program to compare the two strings up to specified length using strncmp ()
function.
#include< stdio.h>
main()
{
char str[10], tar[10];
int diff, n;
printf(“Enter the 1st string”);
gets(sr);
printf(“Enter the 2nd string”);
gets(tar);
printf(“Enter the no. of characters to be compared”);
scanf(“%d”,&n);
diff = strncmp(sr, tar, n);
if(diff = = 0)
puts (“Identical strings”);
else
puts(“Not identical”);
}
Output:
strlwr() function: This function can be used to convert any string to a lowercase.
void main()
{
char upper[15];
clrscr();
printf(“Enter a string in uppercase”);
gets(upper);
printf(“After strlwr() %s, strlwer(upper));
}
Output:
ABCDEFG
Abcdefg
strupr()function : This function is same as strlwrl, but the difference is that strupr()
converts lowercase string to uppercase.
void main(){
char lower[15];
clrscr();
printf(“Enter a string in uppercase”);
gets(lower);
printf(“After strlwr() %s, strupr(lower));
}
Output:
Abcdefg
ABCDEFG
strdup() function: This function is used to create duplicate string for a given string. The
duplicate string is stored at the allocated memory which is pointed by a pointer variable.
The two strings original string and duplicate string stored at different locations but contain
same data.
The format of this function is text2 = strdup (text1); where text1 is string and text2 is a
pointer.
void main(){
char text1[20], *text2;
clrscr();
printf(“Enter text”);
gets(text1);
text2 = strdup(text1);
printf(“Original string = %s \n Duplicate string = %s”, text1, text2);
}
Output:
Enter text: Sunday
Original string = Sunday;
Duplicate string = Sunday;
strchr () function: This function is called with two arguments; they are a string and a
character. If the character exists in the string, then it finds the position of the character
within the string and returns the pointer to a position (in other words address of the
character within the string). If the character does not exist in the string then it returns null
value.
Syntax:
Where string is a character array, ch is character variable, and chp is a pointer which
collects address returned by strchr() function.
Sample program to find the first occurrence of a given character in a given string.
void main()
{
char string [30]; ch, *chp;
clrscr();
printf(“Enter the text”);
gets(string);
printf(“\nEnter the character to find”);
ch = getchar();
chp = strchr(string, ch);
if(chp)
printf(“\ncharacter %c found in string”,ch);
else
printf(“otherwise not found”);
}
Output:
Enter the text Programming
Enter the character to find a
Character a found in string
Explanation: In the above program strchr returns the address of ch in the string which is
stored in chp. The pointer variable chp is checked if it contains address then it prints
character found otherwise not found.
strstr () function: This function is used to find a string within the another string. If the
second string exists in the first string then it returns the pointer location from where the
second string starts in the first string or in other words this function returns the staring
address of the second string starts in the first string.
Sample program to find the first occurrence of a given string in a given string.
void main()
{
char string1 [30]; string2[30], *chp;
clrscr();
printf(“Enter the text”);
gets(string1);
printf(“\nEnter the second string to find”);
gets(string2);
chp = strstr(string1,string2);
if(chp)
printf(“\nstring2 %s is found in string”,string2);
else
printf(“otherwise not found”);
}
Output:
Enter the text Programming
Enter the string to find gram
String gram found in string
Explanation: In the above program if the second string exists in the text. Then it finds
starting location of the second string within the first string which is stored in the second
string. The returned pointer is checked if the string is found then string found is printed
otherwise not found.
strrchr () function : This function finds the last occurrence of a given string in the given
string. In the string References, the last occurrence of the e is in between c & s, here the
address of e is returned.
Sample program to find the first occurrence of a given string in a given string.
void main()
{
char string [30];ch, *chp;
clrscr();
printf(“Enter the text”);
gets(string1);
printf(“\nEnter the second string to find”);
ch = getchar();
chp = strchr(string1,ch);
if(chp)
printf(“\nstring2 %s is found in string”,string2);
else
printf(“otherwise not found”);
}
Output:
Enter the text references
Enter the string to find e
Character e found in string
Explanation: In the above program the character e which is the last occurrence is found
then, the pointer to that character is returned. If not found it returns null.
strcat () function : this function concatenates two string. The target string is appended
to the source string. For example two strings lower and case are concatenated to give
lowercase.
Explanation: In the above program the function strcat is called two times. First time when
strcat is called the function concatenates LOWER & space. Second time function strcat
concatenates “LOWER “ & CASE to give string “LOWER CASE”.
strncat () function : Instead of concatenating entire text2 to the text1. We can select
specified length of characters from the text2, the resultant text is concatenated to the
text1. For example two string Micro & first 4 characters from the text software is to be
concatenated to give text Microsoft. Then this function can be used as follows.
void main()
{
char text [30], text2[30];
int n;
clrscr();
printf(“Enter the text”);
gets(text1);
printf(“\nEnter text2”);
gets(text2);
printf(“\n Enter the no. of character to be appended from the text2”);
scanf(“%d”,&n);
strncat(text1,text2,n);
printf(“ %s \n “, text1);
}
Output:
Enter the text Micro
Enter the text2 Software
Enter the number of characters to be appended from the text2 4
Microsoft
Explanation: In the above program the function strncat is called with 3 parameters text1,
text2 and number of characters to be appended from the text2. Here the text is Micro and
text2 is software & number of characters are 4. Finally we get Microsoft.
void main()
{
char text [15];
clrscr();
puts(“Enter string”);
gets(text);
puts(“Reverse string”);
puts(strrev(text));
}
Output:
Enter the text Programming
Reverse string gnimmargorP
Explanation: In the above program the function strrev is called with parameter
Programming. The function reverses the entered string to gnimmargorP.
strset () function : This function replaces every character of a string with the given
character by the programmer. For example using this function we can replace every
character of a string Microsoft to jjjjjjjjj.
The syntax is
sample program that replaces all characters in a string Microsoft with the character j
void main(){
char string[15];
clrscr();
puts(“Enter string”);
gets(string);
puts( Enter symbol for replacement “);
scanf(“%c”, & symbol);
strset(string, symbol);
printf(“After strsetc %s \n “, string”);
}
Output:
Enter string: microsoft
Enter symbol for replacement: j
After function strset jjjjjjjjj
Explanation: The above program reads the string and symbol to be replaced. The string
& the character is passed to the function strset. This function relaces every character of
the string microsoft with the given character j. Then it displays jjjjjjjj.
strnset () function :This function works same as the above function strset but replaces
the characters of specified length.
The syntax:
sample program that replaces first four characters of a string Microsoft with the character
j.
void main(){
char string[15];
int n;
clrscr();
puts(“Enter string”);
gets(string);
puts( “\nEnter symbol for replacement “);
scanf(“%c”, & symbol);
puts(“\nEnter number of characters that want to be replaced“);
scanf(“%d”,n);
strnset(string, symbol,n);
printf(“After strnset %s \n “, string”);
}
Output:
Enter string: microsoft
Enter symbol for replacement: j
After function strset jjjjosfot
Explanation: The above program reads the string, symbol to be replaced & number of
characters. The string, the character & number of characters are passed to the function
strnset. This function replaces first four characters of the string microsoft with the given
character j. Then it displays jjjjosoft.
strspn () function :This function used to find the difference between different strings. For
example take two strings source string & target string. The source string is microsoft and
target string is microwave. The first five characters are same from the fifth character the
two strings are differ. Then the function returns the position of the source string which is
5. Hence the function returns the position of the string from where the source string does
not match with the target one.
Format is
strspn(string 1, string2);
sample program which displays the characters length of the two strings have mismatch.
void main()
{
char stra [10] , strb [10];
int length;
clrscr();
printf(“first string”);
gets(stra);
printf(“second string”);
gets(strb);
length = strspn ( stra, strb);
printf(“ After %d chars there is mismatch”, length);
}
Output:
First string: Microsoft
Second string: Microwave
After 5 characters there is mismatch
Explanation: The program reads two strings and passes them to the function strspn. This
function checks the two strings and returns an integer number which indicates the
mismatch of a character position. From that character the string is differed.
strpbrk () function (String pointer break): This function returns the sub string of a given
string. For example the micro is the substring of the string microsoft. This function
searches the first occurrence of the character in a given string and then it displays the
string starting from that character.
void main(){
char * ptr;
char text1[20], text[2];
printf(“Enter string”);
gets(text1);
printf(“Enter character”);
gets(text2);
ptr = strbrk (text1, text2);
puts(“String from given character”);
printf(“%s”,ptr);
}
Output:
Enter string: microsoft
Enter character: s
String from given character: soft
Explanation: The above program reads a string microsoft and character s. when these
values are passed to the function strpbrk. The function returns a substring soft.