MODULE-III
ARRAYS & STRINGS
Definition: An array is a collection of elements of same type that share a common name. (Or) An array
is a collective name given to a group of similar quantities.
The elements of an array are stored in contiguous memory locations. The lowest address
corresponds to the first element and highest address to the last element. The advantage of using
arrays is that an array reduces the usage of a number of variables in a program.
In ‘C language, arrays are classified into two types. They are
1. One Dimensional Arrays
2. Multi Dimensional Arrays
ONE DIMENSIONAL ARRAY
When an array is declared with only one dimension (subscript) then it is called “One
dimensional array” or “single dimensional array”.
Declaring one dimensional Array:
The general format of declaring a one dimensional array is as follows:
Syntax:
datatype arrayname[size] ;
In the above syntax,
The datatype is any valid data type of C language. An array can hold all the values based on the
specified data type.
The ‘arrayname’ is an identifier that specifies name of the array variable. All the elements will
share this variable name.
The ‘size’ indicates maximum number of elements that an array can hold. It must be a positive
integer constant.
Example-1: int a[5];
The above declaration reserves 5 contiguous memory locations of integer data type for the
array ‘a’. The conceptual view for the above declaration is as shown below:
0 1 2 3 4
a[0] a[1] a[2] a[3] a[4]
Example-2: float height[50]; declares the height to be an array containing 50 real elements.
Example-3:char name[10]; declares the name as a character array (string) variable that can be hold a
maximum of 10 characters. Suppose the variable name contains the string “WELL DONE”, each
character of the string is treated as an element of the array name and is stored in the memory as
follows:
‘W’ ‘E’ ‘L’ ‘L’ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’
Every character string is terminated by a null character (‘\0’). When declaring character arrays, we
must always allow one extra element space for the null terminator.
1
Initialization Of One Dimensional Array: While declaring an array, we can initialize it with some
values. The general format to initialize one dimensional array is as follows:
Syntax: datatype array name[size] = {V0, V1, …, Vn} ;
Here, V0, V1, …, Vn are the initial values of the specified array. If we omit the values then an array contains
garbage values. The number of values must be less than or equal to the size of the array. When there are few
values then the remaining elements are assigned with zeros.
Ex: a[0] a[1] a[2] a[3] a[4]
1. int a[5] = {78, 34, 98, 90, 124}; 78 34 98 90 124
2. int a[5] = {30, 25, 40};
a[0] a[1] a[2] a[3] a[4]
30 25 40 0 0
Unsized one dimensional arrays:
While declaring an array, if ‘size’ is omitted then that array is treated as unsized array. However unsized
arrays must be initialised. Based on the number of values in the initialisation, the size is automatically
substituted to the array.
Ex: int a[ ] = {78, 34, 98, 90, 124};
In this example, an array is initialised with 5 values. Hence the array size is 5.
Accessing and referencing one dimensional arrays:
A specific element in an array is accessed by an index (also called subscript or dimension). The array
index starts from 0 i.e., the first element in the array is numbered 0, and the last element is 1 less than the size
of the array. The amount of memory required to hold an array is directly related to its type and size.
Each subscript must be expressed as non-negative integer. The subscript values must be enclosed
within square brackets. The subscript values can be constant, variable or an expression.
Example: The ‘n’ elements of an array ‘num’ can be accessed as follows:
num[0], num[1], num[2], …, num[n-1]
(OR)
The above values can be read using a loop variable as follows:
for(i=0;i<=n-1;i++)
scanf(“%d”,&num[i]);
Ex: C Program to read and print the array elements
#include<stdio.h>
#include<conio.h>
void main()
{ int i,a[5];
clrscr();
printf(“Enter 5 number \n”);
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);
printf(“Array elements are \n”);
for(i=0;i<5;i++)
printf(“%d\n”,a[i]);
getch();
}
OUTPUT: Enter 5 Numbers:10 20 30 40 50
Array elements are: 10 20 30 40 50
Multi-Dimensional Arrays:
2
An array which has more than one dimension is called a multi-dimensional array. Multi dimensional
arrays are classified as two-dimensional, three-dimensional, four-dimensional and so on.
TWO-DIMENSIONAL ARRAYS
When an array uses only two subscripts then it is called “two-dimensional array”. A two-dimensional
array is an array of one-dimensional arrays. It can be viewed as table of elements which contains rows and
columns. A two-dimensional array is useful for matrix operations.
Declaring Two-Dimensional Array:
The general format of declaring a two dimensional array is as follows:
Syntax:
datatype arrayname[rowsize][columnsize] ;
In the above syntax,
The datatype is any valid data type of C language. An array can hold all the values based on the
specified data type.
The ‘arrayname’ is an identifier that specifies name of the array variable. All the elements will share
this variable name.
The ‘rowsize’ indicates maximum number of rows and ‘column size’ indicates number of columns in a
row. Example: int a[4][3];
Here, it reserves 12 (4 rows x 3 columns) integer type memory locations for the array ‘a’. The
conceptual view for the above declaration is as shown below:
a[4][3]
0 1 2
0
1
2
3
Initialisation Of Two Dimensional Array:
While declaring an array, we can initialise it with some values. The general format to initialise two
dimensional array is as follows:
Syntax:
datatype arrayname[rowsize][columnsize] = {{row1 values}, {row2 values}, …, } ;
Here, If we omit the values then an array contains garbage values. The number of values must be less
than or equal to the size of the array. When there are few values then the remaining elements are assigned
with zeros.
Example-1:
int a[2][3] = { {4, 6, 8}, {1, 3, 5}};
This example initializes the array ‘a’ with the given values as shown below:
a 0 1 2
0 4 6 8
1 1 3 5
Example-2:
int a[2][3] = { {4, 8}, {5}};
This example initializes the array ‘a’ with the given values as shown below:
a 0 1 2
3
0 4 8 0
1 5 0 0
Accessing and referencing two dimensional arrays:
Each two dimensional array element is referred or accessed by specifying the array name followed by
two subscripts. The subscripts must be enclosed within square brackets.
For example,
A[0][0] refers to the first element in the two dimensional array.
A[rowsize-1][colsize-1] refers to the last element of the array.
The remaining elements can be accessed as a[0][1], a[2][3], a[1][2] and so on.
The two dimensional array that contains ‘m’ rows and ‘n’ columns can be read using loops as follows:
for(i=0;i<=m-1;i++)
for(j=0;j<=n-1;j++)
scanf(“%d”,&a[i][j]);
Ex:C Program to find sum of two matrix
#include<stdio.h>
main() {
int i, j, mat1[10][10], mat2[10][10], mat3[10][10];
int row1, col1, row2, col2;
printf("\nEnter the number of Rows of Mat1 : ");
scanf("%d", &row1);
printf("\nEnter the number of Cols of Mat1 : ");
scanf("%d", &col1);
printf("\nEnter the number of Rows of Mat2 : ");
scanf("%d", &row2);
printf("\nEnter the number of Columns of Mat2 : ");
scanf("%d", &col2);
/* Before accepting the Elements Check if no of
rows and columns of both matrices is equal */
if (row1 != row2 || col1 != col2) {
printf("\nOrder of two matrices is not same ");
exit(0);
}
//Accept the Elements in Matrix 1
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf("Enter the Element a[%d][%d] : ", i, j);
scanf("%d", &mat1[i][j]);
}
}
//Accept the Elements in Matrix 2
for (i = 0; i < row2; i++)
for (j = 0; j < col2; j++) {
printf("Enter the Element b[%d][%d] : ", i, j);
scanf("%d", &mat2[i][j]);
}
//Addition of two matrices
for (i = 0; i < row1; i++)
for (j = 0; j < col1; j++) {
mat3[i][j] = mat1[i][j] + mat2[i][j];
4
}
//Print out the Resultant Matrix
printf("\nThe Addition of two Matrices is : \n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf("%d\t", mat3[i][j]);
}
printf("\n");
}
return (0);
}
OUTPUT:
Enter the number of Rows of Mat1 : 3
Enter the number of Columns of Mat1 : 3
Enter the number of Rows of Mat2 : 3
Enter the number of Columns of Mat2 : 3
Enter the Element a[0][0] : 1
Enter the Element a[0][1] : 2
Enter the Element a[0][2] : 3
Enter the Element a[1][0] : 2
Enter the Element a[1][1] : 1
Enter the Element a[1][2] : 1
Enter the Element a[2][0] : 1
Enter the Element a[2][1] : 2
Enter the Element a[2][2] : 1
Enter the Element b[0][0] : 1
Enter the Element b[0][1] : 2
Enter the Element b[0][2] : 3
Enter the Element b[1][0] : 2
Enter the Element b[1][1] : 1
Enter the Element b[1][2] : 1
Enter the Element b[2][0] : 1
Enter the Element b[2][1] : 2
Enter the Element b[2][2] : 1
The Addition of two Matrices is :
246
422
242
Differences between simple and array variables:
Simple Variable Array Variable
A simple variable creates only one location in the memory of A array variable creates contiguous memory locations
any data type of same data type
A simple variable can hold only one value A array variable can hold many values
A simple variable is declared as follows: A array variable is declared as follows:
datatype variable; datatype arrayname[size];
The conceptual view of a simple variable is as follows: The conceptual view of an array variable is as follows:
Variable Arrayname
……
5
Example: Example:
int num; int num[10];
Here, variable ‘num’ can hold only one value Here, variable ‘num’ can hold 10 values
A simple variable can referred simply by its name An array variable must be referred with array name
followed by subscript enclosed within square brackets.
Differences between one-dimensional and two-dimensional arrays:
One-Dimensional Array Two-Dimensional Array
A one-dimensional array is a group of elements A two-dimensional array is a group of one-
of same type. dimensional array of same type
A one-dimensional array must be declared by A two-dimensional array must be declared by
arrayname followed by only one subscript arrayname followed by 2 subscripts
A one-dimensional array is declared as follows: A two-dimensional array is declared as follows:
datatype arrayname[size]; datatype arrayname[rowsize][colsize];
Example: Example:
int num[4]; int num[3][4];
Here, variable ‘num’ can hold 4 values Here, variable ‘num’ can hold 12 (3x4) values
The conceptual view for the above example is as
The conceptual view for the above example is as follows:
follows:
A one-dimensional array must be referred by A one-dimensional array must be referred by
arrayname followed by only one subscript arrayname followed by one or two subscripts
Initialisation of one-dimensional array is as Initialisation of two-dimensional array is as
follows: follows:
int num[4]={10, 20, 30, 40}; int num[2][2]={{10, 20}, {30, 40}};
Passing Single Dimensional Array to Functions
In ‘C’ an entire array can’t pass as an argument to a function. However pass a pointer to an
array by specifying the arrays name without an index. For example the following program fragment
passes the address of i to fun1().
int main()
{ int i[10];
fun1(i);
/* …………..*/
}
If a function receives a pointer to a single dimensional array, declare its formal parameter in
one of three ways. as a Pointer, as a Sized Array or as an Unsized Array. For example, to receive ‘i’, a
function called fun1() can be declared as
Void fun1(int *x) Void fun1(int x[10]) Void fun1(int x[ ])
/* Pointer*/ /* Sized Array*/ /* Unsized Array*/
{ { {
6
-------- -------- --------
------- ------- -------
} } }
All three declaration methods produce similar results because each tells the compiler that an
integer pointer is going to be received. Actually the first declaration uses a pointer. The second
employs that standard array declaration. In final declaration simply specifies that an array of type int
of some length is to be received. The length of the array does not matter as for as the function is
concerned because c performs No bounds checking. In fact as for as the compiler is concern.
void fun1(int x[32])
{
--------
-------
}
Also works because the compiler generates code that instruct fun1() to receive a pointer it does not
actually creates a 32 element array.
Ex: Add and display the result of 5 numbers given the input using array to function concept
#include<stdio.h>
#include<conio.h>
void add(int, int[])
main()
{
int a[5],i,n=5;
printf(“Enter 5 values:”);
for(i=1;i<=5;i++)
scanf(“%d”,&a[i]);
add(n,a);
}
void add(int x,int a[])
{ int sum=0;
for(i=1;i<=5;i++)
sum=sum+a[i];
printf(“sum =%d”,sum);
}
Output:
Enter 5 Values: 10 20 30 40 50
Sum=150
STRINGS
A string is a sequence of one or more characters. Any group of characters enclosed within double
quotes is a string constant. In ‘C’ language, strings are manipulated using arrays and pointers.
Ex: “Hello” “Computer Science” etc.
A string is a one dimensional array of characters terminated by a null (\0) character. The null character
is stored at the end of array of characters to mark the end of the string. If an array is used to store the strings
7
then that array is often called “string variable”. A string that is not terminated by ‘\0’ is not really a string, but it
is only a collection of characters.
Operations on strings: The common operations performed on strings are:
i. Reading and writing strings
ii. Combining strings together (concatenation)
iii. Copying one string to another
iv. Comparing strings for equality
v. Extracting a portion of string (substring)
vi. Finding the number of characters in a string (length)
Declaring a String Variable:
To manipulate strings, an array must be declared with character data type. A string can be declared as
follows:
Syntax: char arrayname[size];
The ‘size’ is the number of characters in the array.
Example:
char name[40]; char city[15]; etc.
Initializing a String Variable:
1. A string of characters can be stored in an array as follows:
Ex: 1. char city[6] = {‘D’,’E’,’L’,’H’,’I’,’\0’};
2. char city[6] = “DELHI”;
(OR)
char city[] = “DELHI”;
In the example-2, the null character is not needed. The C compiler automatically inserts ‘\0’ character at the
end. So, the conceptual view for the above examples is as shown below:
D E L H I \0
2. A string can be initialized using pointers as follows:
Ex: char *city = “DELHI”;
Here, it stores the string “DELHI” into memory and assigns the starting location address to the pointer
variable ‘city’. The conceptual view for the above example is as shown below:
city 4650 4651 4652 4653 4654 4655
4650 D E L H I \0
Array of Strings (or) Two-dimensional character type array:
To store more than one string in the array, then the array can be declared as follows
char arrayname[size1][size2];
Here, ‘size1’ specifies the number of strings and ‘size2’ refers the number of characters in each string.
Example: char city[3][10] = {“DELHI”,”BANGALORE”,”CHENNAI”};
This example reserves 3 memory locations to store 3 strings. Each string may contain 10 characters (10
bytes). The conceptual view for the above declaration is
City[0] D E L H I \0
City[1] B A N G A L O R E \0
City[2] C H E N N A I \0
Input-Output Operations on Strings:
Scanf( ) and Printf( ) functions:
8
Strings can be read and write using formatted I/O functions by the format character “%s”. While using
“%s” character, the address operator and subscript should not be specified for the array.
When %s character is used with scanf( ) function, it terminates its input at the first white space
character (white space characters are blanks, tabs and carriage return i.e.‘\n’). For example, if we input “NEW
DELHI”, then it takes only “NEW”.
Example:
#include<stdio.h>
Main( )
{ char name[30];
printf(“Enter a string “);
scanf(“%s”,name);
printf(“%s”,name);
}
gets( ) and puts( ) Functions:
These functions are also used to read and write strings. The gets( ) function reads a string upto carriage
return i.e. ‘\n’ pressed. The puts( ) functions writes the specified string on the monitor. These functions will not
require any format character to read and write strings.
Example:
#include<stdio.h>
Main( )
{ char name[30];
printf(“Enter a string “);
gets(name);
puts(name);
}
Built-In String Functions:
In ‘C’ language, there are several function are used to manipulate strings. These functions are included
in “string.h” file. The following are some of the most commonly used string functions:
1. Strlen( ):
This function finds the length of the given string. It means it counts and returns the number of
characters present in the string. The output of this function is an integer.
Syntax: strlen(string); Where ‘string’ is constant or array variable.
Example: #include<stdio.h>
#include<string.h>
main( )
{ int n;
char name[10] = “ABCDE”;
n = strlen(name);
printf(“length = %d”, n);
} Output 5
2. Strrev( ) This function is used to reverse all the characters in the given string except null character.
Syntax: strrev(string); Where ‘string’ is constant or array variable.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char name[10] = “ABCDE”;
strrev(name);
9
puts(name);
}
Output EDCBA
3. Strlwr( ) This function converts all the uppercase letters in the given string into lowercase.
Syntax: strlwr(string); Where ‘string’ is constant or array variable.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char name[10] = “aBcDe”;
strlwr(name);
puts(name);
}
Output abcde
4. Strupr( ) This function converts all the lowercase letters in the given string into uppercase.
Syntax: strupr(string); Where ‘string’ is constant or array variable.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char name[10] = “aBcDe”;
strupr(name);
puts(name);
}
Output ABCDE
5. Strcpy( ) This function copies the contents of one string (source) to another string (destination). The
contents of the source string are unchanged.
Syntax: strcpy(string1, string2);
Where ‘string1’ is destination string and ‘string2’ is source string. The contents of string2 are copied to
string1.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char a[10] = “ABCDE”;
char b[10]; strcpy(b, a); puts(b); }}
The above example copies the contents of ‘a’ to ‘b’. Hence the output is ABCDE.
6. Strcat( ) This function appends the contents of one string (source) to another string (destination). This is
called concatenation of two strings. The contents of the source string are unchanged.
Syntax: strcat(string1, string2); Where ‘string1’ is destination string and ‘string2’ is source string. The
contents of string2 are appended to string1.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char a[30] = “ABC”;
char b[30] = “DEF”;
10
strcat(b, a);
puts(b);
}
The above example append the contents of ‘a’ to ‘b’. Hence the output is DEFABC
7. Strcmp( ) Function:
This function is used to compare two strings.
Syntax: strcat(string1, string2);
Here,
1. If string1 is equal to string2 then it returns value 0
2. If string1 is less than string2 then it returns a negative (less than 0) value.
3. If string1 is greater than string2 then it returns positive (greater than 0) value.
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char a[30], b[30];
int c;
printf(“Enter First String”);
gets(a);
printf(“Enter Second String”);
gets(b);
c = strcmp(a, b);
if (c = = 0)
printf(“String1 and string2 are equal”);
else
if (c < 0)
printf(“String1 is less than string2”);
else
if (c > 0)
printf(“String1 is greater than string2”);
}
Write a C Program to find sum of two matrix?
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
11
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}
Output
Enter the number of rows (between 1 and 100): 2
Enter the number of columns (between 1 and 100): 3
Enter elements of 1st matrix:
Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element b11: -4
Enter element b12: 5
Enter element b13: 3
Enter element b21: 5
Enter element b22: 6
Enter element b23: 3
Sum of two matrices:
-2 8 7
10 8 6
Write a C Program to find subtraction of two matrix?
#include<stdio.h>
#include<conio.h>
int main()
{
12
int mat1[3][3], mat2[3][3], matSub[3][3], i, j;
printf("Enter First 3*3 Matrix Elements: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf("%d", &mat1[i][j]);
}
printf("Enter Second 3*3 Matrix Elements: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf("%d", &mat2[i][j]);
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
matSub[i][j] = mat1[i][j] - mat2[i][j];
}
printf("\nThe Subtraction Result is:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf("%d ", matSub[i][j]);
printf("\n");
}
getch();
return 0;
}
Largest Element in an array
#include <stdio.h>
int main() {
int n;
double arr[100];
printf("Enter the number of elements (1 to 100): ");
13
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%lf", &arr[i]);
}
// storing the largest number to arr[0]
for (int i = 1; i < n; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];
}
}
printf("Largest element = %.2lf", arr[0]);
return 0;
}
Output
Enter the number of elements (1 to 100): 5
Enter number1: 34.5
Enter number2: 2.4
Enter number3: -35.5
Enter number4: 38.7
Enter number5: 24.5
Largest element = 38.70
Write a C program to copy the value of an array to another?
#include<stdio.h>
int main()
{
int i, Size, a[20], b[20];
printf("\n Please Enter the Array Size \n");
scanf("%d", &Size);
printf("\n Please Enter the Array Elements \n");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
/* copying one array to another */
for(i = 0; i < Size; i++)
{
b[i] = a[i];
}
printf("\n Elements of Second Array are: \n");
for(i = 0; i < Size; i++)
{
printf("\n Value Inside Array b[%d] = %d", i, b[i]);
14
}
return 0;
}
.Write a C program to find the product of two matrix
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("multiply of the matrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
15
}
Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18
16