0% found this document useful (0 votes)
7 views37 pages

Unit 4 Itsgsjdlhxlhdkyrhdkgzkgepyezvdmgdkrnvzm

The document provides an overview of arrays in C programming, explaining their definition, properties, advantages, and types including one-dimensional, two-dimensional, and multi-dimensional arrays. It covers array declaration, accessing elements, entering data, and printing values, along with examples of initialization methods. The document emphasizes the importance of arrays for storing similar data types and their efficient access through indices.

Uploaded by

monkey0d0luffy5
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)
7 views37 pages

Unit 4 Itsgsjdlhxlhdkyrhdkgzkgepyezvdmgdkrnvzm

The document provides an overview of arrays in C programming, explaining their definition, properties, advantages, and types including one-dimensional, two-dimensional, and multi-dimensional arrays. It covers array declaration, accessing elements, entering data, and printing values, along with examples of initialization methods. The document emphasizes the importance of arrays for storing similar data types and their efficient access through indices.

Uploaded by

monkey0d0luffy5
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/ 37

M.B.E.

Society’s College of Engineering

Unit 4:- Arrays in C


An array is defined as the collection of similar type of data items stored at contiguous memory
locations and elements can be accessed randomly using indices of an array.. Each storage
location in an array is called as array element. The data elements are addressed by common
name. Arrays are the derived data type in C programming language which can store the primitive
type of data such as int, char, double, float, etc. It also has the capability to store the collection of
derived data types, such as pointers, structure, etc. The array is the simplest data structure where
each data element can be randomly accessed by using its index number. C array is beneficial if
you have to store similar elements. An array is declared by writing data types followed by the
size[dimension] in brackets. Eg:-int a[10];

Arrays are also called as subscripted variables. You can use array subscript (or index) to access
any element stored in array. Subscript starts with 0, which means arr[0] represents the first
element in the array arr. Here, the dimension means the number of subscripts required to
represent the elements in array.

C array is beneficial if you have to store similar elements.

The subscript of an array must be always a positive integer number.

Example where arrays are used,

 to store list of Employee or Student names,


 to store marks of students,
 or to store list of numbers or characters etc.

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 1


M.B.E.Society’s College of Engineering

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.

Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Types of arrays:-

1. Single/One dimensional array


2. Two dimensional array
3. Multidimensional array

Declaration of an array:-

We know that all the variables are declared before the are used in the program. Similarly, an
array must be declared before it is used. During declaration, the size of the array has to be
specified. The size used during declaration of the array informs the compiler to allocate and
reserve the specified memory locations.

General form of array declaration is,

data-type variable-name[size];

/* Example of array declaration */

int arr[10];

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 2


M.B.E.Society’s College of Engineering

Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr
can only contain 10 elements of int type. Index of an array starts from 0 to size-1 i.e first element
of arr array will be stored at arr[0] address and the last element will occupy arr[9].

Remember, the dimension of an array must be constant. Hence the following declarations are
wrong.

Ex: void main() Ex: void main()

{ {

int n; int n=10;

int a[n]; int a[n];

} }

Until we declare a size of a constant, it is not accepted. Following is correct method.

void main()

const int n=10;

int a[n];

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 3


M.B.E.Society’s College of Engineering

Accessing elements of array:-

- The single element can be accessed by specifying the subscript(index) number in the
bracket following the array name. the number represents the position of that element in
the array.
- The element indices start from 0, where first array element is a[0], second array element
is a[1]and so on.
i) Entering data into array:- after declaration of array, the data for the array variables
can be entered in the memory by using one of the following methods.
a) Arithmetic (assignment) statement:
 The value of the array variable can be supplied in the memory by use of
arithmetic statement (i.e assignment)
a[0]=1.22;
a[1]=4.51;
a[2]=6.52;
 In this case the memory is filled using arithmetic statement. The above
statements are the arithmetic statement where value of “a” variable is
stored under different memory location indicated by the index number in
the square bracket to represent memory location.
b) scanf statement:
 The value for an array canbe entered by using scanf statement. In this
case the values in array can be altered by including the scanf statement
in for loop.
 Here the loop variable acts as an index. Ex: i will work as an index.
Ex: for(i=0;i<=4;i++)
{
scanf(“%f”,&a[i]);
}
 In the above statement ‘i’ value starts from 0 and ends at 4. It reads5
values of ‘a’ variable.
c) By initializing:
 The array can be given values directly at the time of its declaration as
below. int x[5]={3,5,-3,1,4};
 In this case, the values for array elements are supplied at the point of
declaration and these 5 values will be assigned as;
x[0]=3,x[1]=5,x[2]=-3,x[3]=1,x[4]=4
ii) Printing array variables:-
 The values of array variables can be printed on screen by using printf statement in the
for loop. Here the loop variables act as an index. Eg.’I’ in following case..

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 4


M.B.E.Society’s College of Engineering

 Following are methods of printing values.


a) for(i=0;i<=4;i++)
{
printf(“x[%d]=%d\n”,i,x[i]);
}
In this method the values of x[0] to x[4] will be printed as:
x[0]=3
x[1]=5
x[2]=-3
x[3]=1
x[4]=4

b) for(i=0;i<=4;i++)
{
printf(“%d\t”,x[i]);
}

In this case the value of x[0] to x[4] will be printed as:

3 5 -3 1 4

/* Program for One dimensional array */

#include<stdio.h>

#include<conio.h>

void main()

float avg, sum=0;

int i;

int marks[5]; /* array declaration*/

clrscr();

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

printf ("\n Enter marks ");

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 5


M.B.E.Society’s College of Engineering

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

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

sum = sum + marks[i];

avg = sum /5;

printf ("\n Average marks = % f", avg);

getch();

Two dimensional arrays:-

 A two dimensional array can be used to represent a table of data items consisting of rows
and columns. Two dimensional arrays are also known as matrix.
 The matrix in mathematics is a two dimensional array which uses two dimensions i.e.
row and column. The element of two dimensional array is indicated by the row and
column number in which it is located.
 The element of matrix is written as aij, where i stands for row and j stands for column
number.
Syntax:- datatype variable_name [row_size][column_size];
Ex: int a[3][3];
int b[4][2];
int c[6][9];
float x[10][5];
float y[20][20];
 Remember the capacity of a two dimensional array to store the number of elements is
calculated by multiplying its dimensions i.e. an array int c[6][9] can store 6x9=54
elements.
 The declaration int a[3][3] can be assumed to create a structure as follows in the memory.
’a’ name of matrix.

0 1 2 column
0 22 2 15
Rows 1 9 6 3
2 4 7 12
[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 6
M.B.E.Society’s College of Engineering

 The element 12 can be indicated by using subscripts 2 2 i.e. a[2][2]=12.


i) Entering values in to an array:
The value can be assigned to two dimensional array elements in the same way as in
case of one dimensional array.
a) Arithmetic assignment:-
The element of array can be supplied a value by using arithmetic statement and by
specifying the row and column number.
a[0][0]=8
a[1][2]=-4
b) scanf statement:-
the value can be entered in to an two dimensional array using scanf statement in a
nested for loop, where the outer loop generates the row numbers and inner loop
generates the column number.
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
scanf(“%d”,&a[i][j]);
}
}
Where ‘a’ is two dimensional array. The ‘I’ is varied from 0 to 2 and jis varied
from 0 to 2. Hence all the subscripts of 3x3 matrix is generated using nested for
loop and values are given to the corresponding variables. The 9 values can be
entered in the following format.
3 1 8
4 7 2
6 3 1
All these elements are managed in the form of row and column.
c) By initializing:-
The array values can be entered at the time of declaration in program as.
int a[3][3]={3,1,8,4,7,2,6,3,1}
float b[3][3]={4.4,1.61,2.7,6.2,3.1,2.11,5.2,3.7,1.4}
ii) Printing array elements:-
The two dimensional array can be printed using printf() statement and nested for loop,
where the outer loop generates the row number and inner loop generates the column
number.
for(i=0;i<=2;i++)
{
[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 7
M.B.E.Society’s College of Engineering

for(j=0;j<=2;j++)
{
printf(“%d\t”,a[i][j]);
}
Printf(“\n”);
}
A 3x3 matrix is printed using nested for statement. The ‘i’ is varied from 0 to 2.
When 3 elements of first row are printed by j a new line control ‘\n’ is executed and next
row is printed on new line.

Multi-Dimensional array:-
Multidimensional arrays are often known as array of the arrays.

 C allows arrays of three or more dimensions. A multi-dimensional array has more than
one subscript. A two dimensional array has two subscripts.
 A three dimensional array has three subscripts, and so on. An element of such array is
referenced by three subscripts.
 The basic syntax or, the declaration of multi dimensional array in C Programming is

Data_Type Array_Name[Tables][Row_Size][Column_Size]

 Data_type: It will decide the type of elements it will accept. For example, If we want to
store integer values then we declare the Data Type as int, If we want to store Float values
then we declare the Data Type as float etc
 Array_Name: This is the name you want to give it to Multi Dimensional array in C.
 Tables: It will decide the number of tables an array can accept. Two Dimensional Array
is always a single table with rows and columns. In contrast, Multi Dimensional array in C
is more than 1 table with rows and columns.
 Row_Size: Number of Row elements an array can store. For example, Row_Size =10, the
array will have 10 rows.
 Column_Size: Number of Column elements an array can store. For example,
Column_Size = 8, the array will have 8 Columns.
Ex:- int a[3][3][3]= 27 elements (i.e. 3x3x3)
float n[4][6][2]=48 elements

In 3-D we can declare the array in the following manner :

int arr[3][3][3] =

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 8


M.B.E.Society’s College of Engineering

{ 1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11, 12,
13, 14, 15,
16, 17, 18,
19, 20, 21,
22, 23, 24,
25, 26, 27
};
Initialization of Arrays:-
The different types of initializing arrays:

1. At Compile time
(i) Initializing all specified memory locations.
(ii) Partial array initialization
(iii) Initialization without size.
(iv) String initialization.
2. At Run Time

1. Compile Time Initialization


We can initialize the elements of arrays in the same way as the ordinary variables when they
are declared. The general form of initialization of arrays is
Type array-name[size]={ list of values};

(i) Initializing all specified memory locations:- Arrays can be initialized at the time of
declaration when their initial values are known in advance. Array elements can be
initialized with data items of type int, char etc.

Ex:- int a[5]={10,15,1,3,20};

During compilation, 5 contiguous memory locations are reserved by the compiler for the
variable a and all these locations are initialized as shown in figure.

Fig: Initialization of int Arrays


[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 9
M.B.E.Society’s College of Engineering

Ex:- int a[3]={9,2,4,5,6};//error: no. of initial vales are more than the size of array.

(ii) Partial array initialization:- Partial array initialization is possible in c language. If


the number of values to be initialized is less than the size of the array , then the elements
will be initialized to zero automatically.

Ex:- int a[5]={10,15};

Eventhough compiler allocates 5 memory locations, using this declaration statement; the
compiler initializes first two locations with 10 and 15, the next set of memory locations
are automatically initialized to 0's by compiler as shown in figure.

Fig: Partial Array Initialization

Initialization with all zeros:- Ex: int a[5]={0};

(i) Initialization without size:- Consider the declaration along with the initialization.

Ex:-
char b[]={'C','O','M','P','U','T','E','R'};

In this declaration, eventhough we have not specified exact number of elements to be


used in array b, the array size will be set of the total number of initial values specified.
So, the array size will be set to 8 automatically. the array b is initialized as shown in
figure.

Fig: Initialization

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 10


M.B.E.Society’s College of Engineering

without size Ex:- int ch[]={1,0,3,5} //

array size is 4

(ii) Array initialization with a string: - Consider the declaration with string

initialization. Ex:-

char b[]="COMPUTER";

The array b is initialized as shown in figure.

Fig: Array Initialized with a String

Eventhough the string "COMPUTER" contains 8 characters, because it is a string. It


always ends with null character. So, the array size is 9 bytes (i.e., string length 1 byte for
null character).

Ex:-char b[9]="COMPUTER"; // correct


char b[8]="COMPUTER"; // wrong
2. Run Time Initialization
An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays.
Ex:- scanf can be used to initialize an array.
Int x[3];
Scanf(“%d%d%d”,&x[0],&x[1],
&x[2]);
The above statements will initialize array elements with the values entered through the
key board.
(Or)
for(i=0;i<10;i=i+1)
{
if(i<50)
Sum[i]=0.0;
else
Sum[i]=1.0;
}

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 11


M.B.E.Society’s College of Engineering

The first 50 elements of the array sum are initialized to 0 while the remaining 50 are
initialized to 1.0 at run time.

Two-dimensional arrays of fixed length


An array consisting of two subscripts is known as two-dimensional array. These are often
known as array of the array. In two dimensional arrays the array is divided into rows and
columns,. These are well suited to handle the table of data. In 2-D array we can declare an
array as :
Declaration:- Syntax:
Data_type array_name[row_size][column_size] = {{list of first row elements},
{list of second row elements},….
{list of last row elements}};
Ex:- int arr[3][3];

where first index value shows the number of the rows and second index value shows the
no. of the columns in the array. We will learn about the 2-D array in detail in the next
section, but now emphasize more on how these are stored in the memory.
Initialization:-

int arr[3][3] = {{ 1, 2, 3},{4, 5, 6},{7, 8,9}};

Where first index value shows the number of the rows and second index value shows the
no. of the columns in the array.
How two dimensional arrays can be used to represent matrices.:-
These are stored in the memory as given below.

• Row-Major order Implementation


• Column-Major order Implementation

In Row-Major Implementation of the arrays, the arrays are stored in the memory in terms of the
row design, i.e. first the first row of the array is stored in the memory then second and so on.
Suppose we have an array named arr having 3 rows and 3 columns then it can be stored in the
memory in the following manner :

int arr[3][3];

arr[0][0] arr[0][1] arr[0][2]


arr[1][0] arr[1][1] arr[1][2]
arr[2][0] arr[2][1] arr[2][2]

Thus an array of 3*3 can be declared as follows :

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 12


M.B.E.Society’s College of Engineering

arr[3][3] = { 1, 2, 3,

4, 5, 6,

7, 8, 9 };

and it will be represented in the memory with row major implementation as follows :

1 2 3 4 5 6 7 8 9

In Column-Major Implementation of the arrays, the arrays are stored in the memory in the term
of the column design, i.e. the first column of the array is stored in the memory then the second
and so on. By taking above eg. we can show it as follows :

arr[3][3] = { 1, 2, 3,

4, 5, 6,

7, 8, 9 };

and it will be represented in the memory with column major implementation as follows :

1 4 7 2 5 8 3 6 9

Two-dimensional arrays of variable length

An array consisting of two subscripts is known as two-dimensional array. These are often known
as array of the array. In two dimensional arrays the array is divided into rows and columns,.
These are well suited to handle the table of data. In 2-D array we can declare an array as :

Declaration:- Syntax:
Data_type array_name[row_size][column_size];

Initialization :-

int arr[3][3] ;

Where first index value shows the number of the rows and second index value shows the no. of
the columns in the array.
These are stored in the memory as given below.

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 13


M.B.E.Society’s College of Engineering

arr[0][0] arr[0][1] arr[0][2]

arr[1][0] arr[1][1] arr[1][2]

arr[2][0] arr[2][1] arr[2][2]

Ex:-

To initialize values for variable length arrays we can use scanf statement & loop constructs.

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

for(j=0;j<3;j++)

scanf(“%d”,&arr[i][j]);

Write a program to perform matrix addition.

#include<stdio.h>

void main()

int i,j;int a[2][2]={1,2,3,4};

int b[2][2]={1,2,3,4};

int c[2][2];

clrscr();

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

for(j=0;j<2;j++)

printf("%2d",a[i][j]);

printf("\n\n");

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 14


M.B.E.Society’s College of Engineering

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

for(j=0;j<2;j++)

printf("%d",b[i][j]);

printf("\n\n");

Printf(“\n The addition of given two matrices is\n”); for(i=0;i<2;i++)

for(j=0;j<2;j++)

{
c[i][j]=a[i][j]+b[i][j];

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

for(j=0;j<2;j++)

Printf(“%d”,c[i][j]);

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 15


M.B.E.Society’s College of Engineering

getch();

OUTPUT:

1 2

3 4

1 2

3 4

The addition of given two matrices is

2 4

6 8

/*MATRIX MULTIPLICATION*/

#include<stdio.h> #include<conio.h>

void main()

int a[3][3],b[3][3],c[3][3],i,j,k;

clrscr();

printf("\n enter the matrix elements"); for(i=0;i<3;i++);

for(j=0;j<3;j++);

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

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 16


M.B.E.Society’s College of Engineering

printf("\n a matrix is\n"); for(i=0;i<3;i++)

for(j=0;j<3;j++)

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

printf("\n");

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

for(j=0;j<3;j++)

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

printf("\n b matrix is\n");

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

for(j=0;j<3;j++)

printf("%d\t",b[i][j]);

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 17


M.B.E.Society’s College of Engineering

printf("\n");

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

for(j=0;j<3;j++)

c[i][j]=0;

for(k=0;k<3;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

printf("\n The multiplication of given two matrices is\n"); for(i=0;i<3;i++)

for(j=0;j<3;j++)

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

printf("\n");

getch();

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 18


M.B.E.Society’s College of Engineering

OUTPUT:

enter the matrix elements

1 1 1

1 1 1

1 1 1

2 2 2

2 2 2

2 2 2

A matrix is:

1 1 1

1 1 1

1 1 1

B matrix is:

2 2 2

2 2 2

2 2 2
The multiplication of given two matrices is

6 6 6

6 6 6

6 6 6

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 19


M.B.E.Society’s College of Engineering

Passing array to Function:-


In C programming, a single array element or an entire array can be passed to function. Also, both
one dimensional and multidimensional array can be passed to function as argument. Single
element of an array can be passed in similar manner as passing variable to a function.

Array elements can be passed to function by calling the function using call by value or call by
reference. In call by value we pass values of array elements, whereas in call by reference we pass
address of array elements to the function.

While passing entire array to function, the name of the array is passed as an argument (i.e.
starting address of memory area is passed as argument.)

Strings[Character Array]:-

- Like arrays of integer, float we can have an array of characters. A sequence of characters
is called string.
- The string is a character array stored in continuous memory locations. The strings are
used for manipulating text such as words or sentences.
- C does not support string as a data type. However, it allows to represent strings as
character array.
- The string is a one dimensional array of characters, which is terminated by delimiter \0
(null). Thus, C uses variable-length delimited strings in programs.
- Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the '\0' at the end of the string when it initializes the array.
- The size of character array should be equal to the maximum number of characters in the
string plus one. Each character needs one byte of memory space.

Declaration of strings:

Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax
for declaring a string.

Syntax:- char string_name[size];


Ex:- char city[10];
char name[30];
char line[80];

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 20


M.B.E.Society’s College of Engineering

Initializing strings:-

- A char type variable can hold only single character. Hence to store a string we need an
array because string is a sequence of characters. For example: name, address, month, city
are examples of strings. C handles this type of information using an array of characters.
- It is collection of characters (array of characters). In C, string has dual advantage that it
can be accessed as a string an array when required.
- There are two ways to declare a string in c language. By char array and By string literal

- There are several methods to initialize values for string variables.

- Ex:- char city[8]=”NEWYORK”;


-
- Char city[8]={‘N’,’E’,’W’,’Y’,’O’,’R’,’K’,’\0’};
-
- The string city size is 8 but it contains 7 characters and one character space is for
NULL terminator.
OR

Let's see the example of declaring string by char array in C language.

char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

We can also define the string by the string literal in C language. For example:

char ch[]="javatpoint";

In such case, '\0' will be appended at the end of the string by the compiler.

Difference between char array and string literal

There are two main differences between char array and literal.

1. We need to add the null character '\0' at the end of the array by ourself whereas, it is
appended internally by the compiler in the case of the character array.
2. The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 21


M.B.E.Society’s College of Engineering

Storing strings in memory:-

In C a string is stored in an array of characters and terminated by \0 (null).

A string is stored in array, the name of the string is a pointer to the beginning of

the string. The character requires only one memory location.

If we use one-character string it requires two locations. The difference shown below,

The difference between array & string shown below,

Because strings are variable-length structure, we must provide enough room for
maximum- length string to store and one byte for delimiter.

Why do we need null?

A string is not a datatype but a data structure. String implementation is logical not
physical. String implementation is logical not physical. The physical structure is array in
which the string is stored. The string is variable-length, so we need to identify logical end
of data in that physical structure.

The common operations performed on character strings are:

- Reading and writing strings.


- Combining strings together.
- Copying one string to another.
[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 22
M.B.E.Society’s College of Engineering

- Comparing strings for equality.


- Extracting a portion of a string.

Reading Stirng:-

- The input function scanf can be used with %s format specifier to read in a string of
characters.
char name[20];
scanf(“%s”,name);
- With this scanf statement, it terminates its input on first white space it finds i.e. blank
space, tabs, carriage returns, form feeds etc. for ex: if the name is “Engineering college”,
the scanf statement will read only Engineering in array address, since blank space after
the name “Engineering” will terminate the string.
- In case of character arrays, the ampersand (&) is not required before the variable name
because the name of array itself is a pointer, the base address of the string.
- Using scanf statement the length of the string should not exceed the dimensions of the
character array.

Writing String:

The output function printf can be used with %s format specifier to print string of characters. The
format %s can be used to display an array of character that is terminated by null character.

Printf(“%s”,name); can be used to display the entire contents of the array name.

Ex:- void main()

char name[18],city[15],post[15];

printf(“Enter employee data\n”);

scanf(“%s%s%s”,name,city,post);

printf(“name=%s city=%s post=%s\n”,name,city,post);

String Input/Output Functions:-

C provides two basic methods to read and write strings. Using formatted input/output functions
and using a special set of string only functions.
[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 23
M.B.E.Society’s College of Engineering

Reading strings from terminal:-

(a)Using formatted input/output:- scanf can be used with %s format specification to read a
string. Ex:- char name[10];

scanf(“%s”,name);

Here don’t use ‘&’ because name of string is a pointer to array. The problem with scanf, %s is
that it terminates when input consisting of blank space between them.

Ex:- NEW YORK

Reads only NEW (from above example).

(b) Special set of functions:-


(1) getchar():- It is used to read a single character from keyboard. Using this function
repeatedly we may read entire line of text and stored in memory.
Ex:- char ch=’z’;

ch=getchar();

(2) gets():- It is more convenient method of reading a string of text including blank. The gets
function reads a line from the standard input stream stdin and stores it in memory. The
line consists of all characters up to end including the first newline character(‘\n’). gets()
then replaces the newline character with a null character (‘\0’) before returning the line.
This function reads the input with or without blank space. The gets() allows the user to
enter the space-separated strings.
Ex:-
{
char line[100];

printf(“Input a string”);
gets(line);
printf(“The line entered was: %s”,line);
}
Writing strings on to the screen:-

(1) Using formatted output functions:- printf with %s format specifier we can print strings
in different formats on to screen.
Ex:- char name[10];

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 24


M.B.E.Society’s College of Engineering

printf(“%s”,na

me);

Ex:- char name[10];

printf(“%0.4”,name);

/* If name is JANUARY prints only 4 characters ie., JANU */

Printf(“%10.4s”,name);

printf(“%-10.4s”,name);

(2) Using special set of functions:-


(a) putchar():- It is used to print one by one character. Ex:- putchar(ch);

(b) puts():- It is used to print strings including blank spaces.The puts function writes string to
the standard output stream stdout, replacing the string’s terminating null character (‘\0’)
with a newline character (‘\n’) in the output stream.

Ex:- char line[15]=”Welcome to lab”;

puts(line);

String Manipulating Functions:-

The C library supports a large number of string handling functions that can be used to carry
out many string manipulations. The C program that contains the statements of manipulation of
strings, All of these built-in functions are defined in the header file <string.h> .
Following are most commonly used string handling functions.

Sr. No. Function Description

1) strlen() returns the length of string name.

2) strupr() returns string characters in uppercase.

3) strlwr() returns string characters in lowercase.

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 25


M.B.E.Society’s College of Engineering

4) strrev() returns reverse string.

5) strcpy() copies the contents of source string to destination string.

6) strncpy() Copies n characters of one string into another.

7) strcat() concats or joins first string with second string. The result of the string
is stored in first string.(Appends one string at the end of another string)

8) strncat() Append n characters of one string at the end of another string

9) strcmp() compares the first string with second string. If both strings are same, it
returns 0.

10) strncmp() Compares first n characters of two strings.

11) strcmpi() Compares two strings by ignoring the case

12) strncmpi() Compares first n characters of two strings by ignoring the case

strlen ( ):
strlen() function: This function is used to find the length of the string excluding the NULL
character. In other words, this function is used to count the number of characters in a string. Its
syntax is as follows:
int strlen(string);

Example: char str1[ ] =

“WELCOME”; int n;

n = strlen(str1);

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 26


M.B.E.Society’s College of Engineering

/* A program to calculate length of string by using strlen() function*/

#include<stdio.h>

#include<string.h>

main()

char string1[50];

int length;

printf(“\n Enter any string:”);

gets(string1);

length=strlen(string1);

printf(“\n The length of string=%d”,length);

strupr ( ):
This function converts the given string into upper case. If the string is already in uppercase it
remains as it is.

Syntax: strupr(str);

/*Program to convert a string into upper case*/

#include<stdio.h>

void mystrupr(char*);

void main()

Char word[10]=”Bombay”;

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 27


M.B.E.Society’s College of Engineering

mystrupr(word);

printf(“%s”,word);

void mystrupr(char*p)

while(*p!=’\0’)

if(*p>=97&&*p<=122)

*p=*p-32;

P++;

strlwr():
this function converts the given string into lower case. If it is already in the lower case then it
remains as it is.

Syntax:- strlwr(str);

/*Program to convert a string into lower case*/

#include<stdio.h>

void mystrlwr(char*);

void main()

Char word[10]=”AMbaJoGaI”;

mystrlwr(word);

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 28


M.B.E.Society’s College of Engineering

printf(“%s”,word);

void mystrlwr(char*p)

while(*p!=’\0’)

if(*p>=65&&*p<=90)

*p=*p+32;

P++;

strrev():
this function is used to reverse the given string and stores it at the same place.

Syntax:- strrev(str);

/*Program to reverse a string */

#include<stdio.h>

void mystrrev(char[]);

void main()

Char word[10]=”INDIA”;

mystrrev(word);

printf(“%s”,word);

void mystrrev(char p[])

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 29


M.B.E.Society’s College of Engineering

int n,i,j;

char temp;

n=strlen(p);

for(i=0,j=n-1;i<=(n-1)/2;i++,j--)

temp=p[i];

p[i]=p[j];

p[j]=temp;

strcpy()
This function is used to copy one string to the other. Its syntax is as follows:

strcpy(string1,string2);

where string1 and string2 are one-dimensional character arrays.

This function copies the content of string2 to string1. E.g., string1 contains master and string2
contains madam, then string1 holds madam after execution of the strcpy (string1,string2)
function.

Example: char str1[ ] = “WELCOME”; char str2[ ] =”HELLO”;

strcpy(str1,str2);

/* A program to copy one string to another using strcpy() function */

#include<stdio.h>

#include<string.h>

main( )

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 30


M.B.E.Society’s College of Engineering

char string1[30],string2[30];

printf(“\n Enter first string:”);

gets(string1);

printf(“\n Enter second string:”);

gets(string2);

strcpy(string1,string2);

printf(“\n First string=%s”,string1);

printf(“\n Second string=%s”,string2);

OR

#include<stdio.h>

void mystrcopy(char*,char*);

void main()

char source[10]=”Technology”;

char target[10];

mystrcopy(target,source);

printf(“%s”,target);

void mystrcopy(char*t,char*s)

while(*s!=’\0’)

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 31


M.B.E.Society’s College of Engineering

*t=*s;

s++;

t++;

*t=’\0’;

strcat ( ):
This function is used to concatenate two strings. i.e., it appends one string at the end of the
specified string. Its syntax as follows:

strcat(string1,string2);

where string1 and string2 are one-dimensional character arrays.

This function joins two strings together. In other words, it adds the string2 to string1 and the
string1 contains the final concatenated string. E.g., string1 contains prog and string2 contains
ram, then string1 holds program after execution of the strcat() function.

Example: char str1[10 ] = “VERY”;

char str2[ 5] =”GOOD”;

strcat(str1,str2);

/* A program to concatenate one string with another using strcat() function*/

#include<stdio.h>

#include<string.h>

main()

char string1[30],string2[15];

printf(“\n Enter first string:”);

gets(string1);

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 32


M.B.E.Society’s College of Engineering

printf(“\n Enter second string:”);

gets(string2);

strcat(string1,string2);

printf(“\n Concatenated string=%s”,string1);

OR
#include<stdio.h>

void mystrcat(char*,char*);

void main()

char source[20]=”University”;

char target[40] =”Technological”;

mystrcat (target,source);

printf(“%s”,target);

void mystrcat(char*t,char*s)

while(*t!=’\0’) \* goto end of target*/

t++;

while(*s!=’\0’) /*add source at end of target*/

*t=*s;

s++;
[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 33
M.B.E.Society’s College of Engineering

t++;

*t=’\0’;

strcmp ( ):
This function compares two strings character by character (ASCII comparison) and returns one
of three values {-1,0,1}. The numeric difference is ‘0’ strings are equal otherwise if it is negative
string1 is alphabeticallly above string2 or if it is positive string2 is alphabeticallly above string1.

Its syntax is as follows:

int strcmp(string1,string2);

Example:

char str1[ ] = “ROM”;

char str2[ ] =”RAM”;

strcmp(str1,str2);

(OR)

strcmp(“ROM”,”RAM”);

/* A program to compare two strings using strcmp() function */

#include<stdio.h>

#include<string.h>

main()

char string1[30],string2[15];

int x;

printf(“\n Enter first string:”);

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 34


M.B.E.Society’s College of Engineering

gets(string1);

printf(“\n Enter second string:”);

gets(string2);

x=strcmp(string1,string2);

if(x==0)

printf(“\n Both strings are equal”);

else if(x>0)

printf(“\n First string is bigger”);

else

printf(“\n Second string is bigger”);

OR

#include<stdio.h>

void mystrcmp(char*,char*);

void main()

char source[80];

char target[80];

int n;

gets(source);

gets(target);

n=mystrcmp (target,source);

if(n==0)

printf(“The strings are matching\n”);

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 35


M.B.E.Society’s College of Engineering

else

printf(“The strings are not matching\n”);

printf(“The ASCII difference between first two unmatching char=%d\n”,n);

void mystrcmp(char*t,char*s)

while(*t!=’\0’||*s!=’\0’)

if(*t!=*s)

return(*t-*s);

t++;

s++

getch();

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 36


M.B.E.Society’s College of Engineering

String concepts:-

In general a string is a series of characters (or) a group of characters. While implementation of


strings, a string created in pascal differs from a string created in C language.

1. Fixed-length strings:
When implementing fixed-length strings, the size of the variable is fixed. If we make it
too small we can’t store, if we make it too big, then waste of memory. And another
problem is we can’t differentiate data (characters) from non-data (spaces, null etc).

2. Variable-length string:
The solution is creating strings in variable size; so that it can expand and contract to
accommodate data. Two common techniques used,
(a) Length controlled strings:
These strings added a count which specifies the number of characters in the string.

Ex:-
5 H E L L O

(b) Delimited strings:


Another technique is using a delimiter at the end of strings. The most common
delimiter is the ASCII null character (\0).

Ex:-

[Notes Prepared By Prof. Suryakant B. kendre]Page 1 [Type text] Page 37

You might also like