0% found this document useful (0 votes)
105 views

Unit-3: Arrays

The document discusses arrays in C language. Arrays allow storing a collection of related data items and operating on them using a single name. Arrays must be declared before use which includes specifying the type of elements and maximum size. Individual elements can be accessed using an index. Multi-dimensional arrays allow storing two-dimensional data like matrices by using multiple indices. Strings in C are basically arrays of characters that are stored in contiguous memory locations.

Uploaded by

Chinnari Chinnu
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)
105 views

Unit-3: Arrays

The document discusses arrays in C language. Arrays allow storing a collection of related data items and operating on them using a single name. Arrays must be declared before use which includes specifying the type of elements and maximum size. Individual elements can be accessed using an index. Multi-dimensional arrays allow storing two-dimensional data like matrices by using multiple indices. Strings in C are basically arrays of characters that are stored in contiguous memory locations.

Uploaded by

Chinnari Chinnu
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/ 36

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];

Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49


are valid. In C the array elements index or subscript begins with number zero. So height
[0] refers to the first element of the array. (For this reason, it is easier to think of it as
referring to element number zero, rather than as referring to the first element).

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

for(i=0;i < 100;++i); sum =


sum + grades [i];

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:

type array_name[size]={list of values};

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.

Complete the given points

Accessing the array elements:


(i) Assigning values to array elements: .....................................

(ii) Displaying the array elements: ...........................................

/* Program to count the no of positive and negative numbers*/


#include< stdio.h >
main( )

{
int a[50],n,count_neg=0,count_pos=0,i;
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);

printf(“Enter the elements of the array\n”);


for (i=0;i < n;i++)
scanf(“%d”,&a[I]);
for(i=0;i < n;i++)

if(a[i] < 0)
count_neg++;
else
count_pos++;
}

printf(“There are %d negative numbers in the array\n”,count_neg); printf(“There


are %d positive numbers in the array\n”,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.

The declaration of two-dimensional arrays is as follows:

data-type array-name[row-size][column-size];
int m[10][20];

Here m is declared as a matrix having 10 rows (numbered from 0 to 9) and 20 columns


(numbered 0 through 19). The first element of the matrix is m[0][0] and the last row last
column is m[9][19]

Elements of multi dimension arrays

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]

Initialization of multidimensional arrays

Like the one-dimension arrays, two-dimension arrays may be initialized by following their
declaration with a list of initial values enclosed in braces

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

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}}

By surrounding the elements of each row by braces.

C allows arrays of three or more dimensions. The compiler determines the


maximum number of dimensions. The general form of a multi-dimensional array
declaration is:
date_type array_name[s1][s2][s3]…..[sn];

Where s is the size of the ith dimension.

Some examples are:

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.

2. Write a C program to accept a matrix and determine whether it is a sparse matrix.


A sparse matrix is a matrix where the number of 0s is more than other elements.

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.

5. Write a C program to reverse a given integer number and check whether it is a


palindrome.

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.

int NUM; float salary; char ch;

NUM = 54; salary = 443; ch = ‘A’

Variable NUM Variable salary Variable ch

Data( integer Data (float Data


54 4432 ‘A’
number) number) (char)

Memory Memory Memory


Address location 53002 Address 53321 Address 54001
location 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.

A string is a series of characters treated as a unit. The string has a variable-


length piece of data. All string manipulations are implemented internally assuming that
the string has variable length of data. One of the most common examples of a string is a
name. The nature of the names is that they vary in length. The name may be a person’s
name, a text book’s name or the name of a place. All objects contain some name.

Based on the length of a string, they are of two types, namely, fixed length and variable
length.

Variable length can be divided into length controlled and delimited.

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.

char Ename [7]= { ‘K’,’U’,’M’,’A’,’R’};

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’

There are two limitations with the fixed-length strings

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

Length-controlled strings add a count value which indicates the number of


characters in the string. This count is placed in the starting location of string as shown
below. This count is then used by the string manipulation to choose the actual length of
the data.

Count (Length of String)

9 C o n f u c i u s

Length-controlled string in a memory

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.

The String BOOLE is terminated by null character.

delimiter

B O O L E \0

Delimited string in a memory

C Strings

A string is a variable-length of array characters that is delimited by the null


character (‘\0’). So, string contains characters which are printable characters and one
delimiter at the end of the string which is a non-printable character. In the above figure
the string BOOLE is printable character and null character (\0) is non-printable character.
Other than null delimiter, in some cases programs strings may use formatting characters
as delimiters such as tabs.

So, in C the strings are variable length, delimited strings.

Storing strings:

In C, a string is stored in an array of characters. At the end of the string a delimiter


(‘\0’) is added to indicate the end of the string. The string with delimiter is stored in memory
as shown below.

Beginning of End of string


string delimiter

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.

The String Delimiter


Declarations of int, float and char are as shown below.

Data types

int I;

float f;

char c;

char S[4];

index data structure

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:

String Character Array

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

End of the string character

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 ? ?

Part of the array but not part of the string


In the above case, from the first to the null character is the string. So, the string is
“Good Day”. The rest two locations are ignored.

String Literals

A string literal is also known as string constant which is a sequence of any


characters enclosed between double quotes. The following are 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.

char str1 [] = “C is a high-level language” ;

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).

Strings and characters

A single character can be stored as a character literal or as a string literal.

 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.

A space (‘ ‘) or a null character (‘\0’) indicates the absence of a character. A string


in other hand is a variable length structure. A string that contains no data consists of only
a delimiter.

Difference between strings and characters

Strings Characters

1 We use single quote 1 We use double quote


marks marks

“a” ‘a’

2 A function call is used 2 An assignment operator


(=)is used
char ch[];
char ch;
strcpy(ch,”a”);
ch = ‘a’;

3 An empty string consist 3 The absence of the data


only null delimiter(‘\0’) space is represented by
(‘ ‘) or null character (‘\0’)

4 Program is need to 4 Program is need to


interpret the absence of interpret the absence of
data data

Referencing String literals

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.

Two types of methods are used to declare strings

1) String declaration as an array


2) String pointer declaration

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.

char str [9];

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.

String declaration as an array

Str

However, we can also declare a string as a pointer. In case pointer memory is


allocated only two bytes are allocated for the pointer address; no memory is allocated for
the data.

Fixed memory locations allocated. The name of the string is a pointer location. For
future characters also, memory is allocated.

char * pstr ; pStr Pointer to string

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:

In C initialization of strings can be done in three ways

1) Initialization as string constant


2) Initialization as character pointer
3) Initialization as an array of characters.

Initializing as string constant:

Storing a string constant into a string variable is known as initializing a string.

To store a string constant “Good Day” in a string variable str in C is coded as shown
below.

char str[9] = “ Good Day”;

The above statement is also known as assigning “Good Day” to string str.

Since a string constant is an array of characters, so at the time of initializing (or


assigning) the size of the array need not be mentioned.

char month[] = “January”;

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.

Initializing as a character pointer:

The string is initialized as a character pointer as shown below.

String Pointer variable String literal (or string


constant)

char * pstr = “Good Day”

“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.

String variable Array of characters

char str[9] = { ‘G’,’o’, ’o’, ’d’, ’ ’, ’D’, ’a’, ’y’, ’\0’}

“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.

String and the Assignment Operator

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:

a=… a[5] =… (a)=… *p= …

The lvalue can be modified which is at the right side of the assignment operator.

rvalue which is 5 + 8 cannot be modified, but used to supply a value. The


expression 5 + 8 cannot be modified but can be used to give a value which can be used
for further use. The following are rvalue expression:

5 a+2 a*6 a[2] + 3 a++

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 str1[6] = “Hello”;

char str2[6];

str2 = str1; //compile error

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.

So, third line shows a compilation time error.

Reading and Writing Strings:

C provides a header file string.h to perform string input/output operations. The


different operations are provided by string functions are finding the length of string, copy
the contents of one string to another string variable, joining two different strings, reversing
a string.

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’};

5 char arr1[9] = “welcome”;

6 char arr2[9] = { {‘W’}, {‘E’}, {‘L’}, {‘ ‘}, {‘C’}, {‘O’}, {‘M’}, {‘E’}, {‘\0’};

7 clrscr();

8 printf(“\n array = %s”, arr);

9 printf(“\n array1 = %s”, arr1);

10 printf(“\n array2 = %s”, arr2);

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:

Type Text Below Delhi

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.

The format of strcpy() is strcpy(s2, s1);

Where, s1 is the source string

S2 is the destination string

i.e., s1 is copied to 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()function: This function performs same operation as strcpy().

strncpy copies specified length of characters from source to destination string where as
strcpy function copies the source string to destination string.

The format of the function strncpy is

Strncpy(destination, source, n);

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.

Sample program to compare the two strings using stricmp () function.

#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:

Enter the 1st string computer

Enter the 2nd string COMPUTER

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:

Enter the 1st string computer

Enter the 2nd string laptop

Not Identical
strcmp() function: It performs the same task as stricmp() function. The strcmp() function
discriminates between small and capital letters.

Sample program to compare the two strings using stricmp () function.

#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:

Enter the 1st string computer


Enter the 2nd string Computer
Enter the no. of characters to be compared: 7
Identical strings

strlwr() function: This function can be used to convert any string to a lowercase.

C program to convert uppercase string to lowercase string strlwr()

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:

Chp = strchr (string, ch);

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.

Sample program to concatenate two different given strings.


void main(){
char text [30], text2[30];
clrscr();
printf(“Enter the text”);
gets(text1);
printf(“\nEnter text2”);
gets(text2);
strcat(text1, “ “);
strcat(text1,text2);
chp = strchr(string1,ch);
printf(“ %s \n “, text1);
}
Output:
Enter the text LOWER
Enter the string to find CASE
LOWER CASE

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.

strrev () function :This function reverses the given string.

Sample program that reverses the given string.

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

strset (string, symbol);

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:

strnset (string, symbol, n)

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.

You might also like