Unit 4 Itsgsjdlhxlhdkyrhdkgzkgepyezvdmgdkrnvzm
Unit 4 Itsgsjdlhxlhdkyrhdkgzkgepyezvdmgdkrnvzm
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.
Properties of Array
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
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:-
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.
data-type variable-name[size];
int arr[10];
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.
{ {
} }
void main()
int a[n];
- 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..
b) for(i=0;i<=4;i++)
{
printf(“%d\t”,x[i]);
}
3 5 -3 1 4
#include<stdio.h>
#include<conio.h>
void main()
int i;
clrscr();
getch();
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
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
int arr[3][3][3] =
{ 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
(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.
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.
Ex:- int a[3]={9,2,4,5,6};//error: no. of initial vales are more than the size of array.
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.
(i) Initialization without size:- Consider the declaration along with the initialization.
Ex:-
char b[]={'C','O','M','P','U','T','E','R'};
Fig: Initialization
array size is 4
(ii) Array initialization with a string: - Consider the declaration with string
initialization. Ex:-
char b[]="COMPUTER";
The first 50 elements of the array sum are initialized to 0 while the remaining 50 are
initialized to 1.0 at run time.
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:-
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.
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[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
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.
Ex:-
To initialize values for variable length arrays we can use scanf statement & loop constructs.
for(j=0;j<3;j++)
scanf(“%d”,&arr[i][j]);
#include<stdio.h>
void main()
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");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf("%d",b[i][j]);
printf("\n\n");
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]);
getch();
OUTPUT:
1 2
3 4
1 2
3 4
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();
for(j=0;j<3;j++);
scanf("%d",&a[i][j]);
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]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf("%d\t",b[i][j]);
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];
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
printf("\n");
getch();
OUTPUT:
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
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.
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
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.
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.
A string is stored in array, the name of the string is a pointer to the beginning of
If we use one-character string it requires two locations. The difference shown below,
Because strings are variable-length structure, we must provide enough room for
maximum- length string to store and one byte for delimiter.
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.
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.
char name[18],city[15],post[15];
scanf(“%s%s%s”,name,city,post);
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
(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.
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];
printf(“%s”,na
me);
printf(“%0.4”,name);
Printf(“%10.4s”,name);
printf(“%-10.4s”,name);
(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.
puts(line);
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.
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)
9) strcmp() compares the first string with second string. If both strings are same, it
returns 0.
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);
“WELCOME”; int n;
n = strlen(str1);
#include<stdio.h>
#include<string.h>
main()
char string1[50];
int length;
gets(string1);
length=strlen(string1);
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);
#include<stdio.h>
void mystrupr(char*);
void main()
Char word[10]=”Bombay”;
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);
#include<stdio.h>
void mystrlwr(char*);
void main()
Char word[10]=”AMbaJoGaI”;
mystrlwr(word);
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);
#include<stdio.h>
void mystrrev(char[]);
void main()
Char word[10]=”INDIA”;
mystrrev(word);
printf(“%s”,word);
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);
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.
strcpy(str1,str2);
#include<stdio.h>
#include<string.h>
main( )
char string1[30],string2[30];
gets(string1);
gets(string2);
strcpy(string1,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’)
*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);
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.
strcat(str1,str2);
#include<stdio.h>
#include<string.h>
main()
char string1[30],string2[15];
gets(string1);
gets(string2);
strcat(string1,string2);
OR
#include<stdio.h>
void mystrcat(char*,char*);
void main()
char source[20]=”University”;
mystrcat (target,source);
printf(“%s”,target);
void mystrcat(char*t,char*s)
t++;
*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.
int strcmp(string1,string2);
Example:
strcmp(str1,str2);
(OR)
strcmp(“ROM”,”RAM”);
#include<stdio.h>
#include<string.h>
main()
char string1[30],string2[15];
int x;
gets(string1);
gets(string2);
x=strcmp(string1,string2);
if(x==0)
else if(x>0)
else
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)
else
void mystrcmp(char*t,char*s)
while(*t!=’\0’||*s!=’\0’)
if(*t!=*s)
return(*t-*s);
t++;
s++
getch();
String concepts:-
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
Ex:-