Arrays and Strings
Arrays and Strings
Arrays and Strings
Overview
So far we have used only the fundamental data types, namely char, int, float, double and
variations of int and double. Although these types are very useful, they are constrained by the
fact that a variable of these types can store only one value at any given time. Therefore, they
can be used only to handle limited amounts of data. In many applications, however, we need to
handle a large volume of data in terms of reading, processing and printing. To process such
large amounts of data, we need a powerful data type that would facilitate efficient storing,
accessing and manipulation of data items. C supports a derived data type known as array that
can be used for such applications.
What is an Array?
An array is a fixed-size sequenced collection of elements of the same data type. It is simply a
grouping of like-type data. In its simplest form, an array can be used to represent a list of
numbers, or a list of names. Some examples where the concept of an array can be used:
● List of temperatures recorded every hour in a day, or a month, or a year.
● List of employees in an organization.
● List of products and their cost sold by a store.
● Test scores of a class of students
and so on.
Since an array provides a convenient structure for representing data, it is classified as one of
the data structures in C. Other data structures include structures, lists, queues and trees. A
complete discussion of all data structures is beyond the scope of the syllabus, but we will also
study structures in this unit ahead.
As we mentioned earlier, an array is a sequenced collection of related data items that share a
common name. For instance, we can use an array name salary to represent a set of salaries of
a group of employees in an organization. We can refer to the individual salaries by writing a
number called index or subscript in brackets after the array name.
For example,
salary [10]
represents the salary of a 10th employee. While the complete set of values is referred to as an
array, individual values are called elements. The ability to use a single name to represent a
collection of items and to refer to an item by specifying the item number enables us to develop
concise and efficient programs. For example, we can use a loop construct, discussed earlier,
with the subscript as the control variable to read the entire array, perform calculations, and print
out the results.
We can use arrays to represent not only simple lists of values but also tables of data in two,
three or more dimensions. In this chapter, we introduce the concept of an array and discuss how
to use it to create and apply the following types of arrays.
● One-dimensional arrays
● Two-dimensional arrays
● Multidimensional arrays
Data Structures
C supports a rich set of derived and user-defined data types in addition to a variety of
fundamental types as shown below:
Arrays and structures are referred to as structured data types because they can be used to
represent data values that have a structure of some sort. Structured data types provide an
organizational scheme that shows the relationships among the individual elements and facilitate
efficient data manipulations. In programming parlance, such data types are known as data
structures.
In addition to arrays and structures, C supports creation and manipulation of the following data
structures:
● Linked Lists
● Stacks
● Queues
● Trees
One-Dimensional Arrays
A list of items can be given one variable name using only one subscript and such a variable is
called a single-subscripted variable or a one-dimensional array.
In mathematics, we often deal with variables that are single-subscripted. For instance, we use
the equation
to calculate the average of n values of x. The subscripted variable xi refers to the ith element of
x. In C, a single-subscripted variable xi can be expressed as x[1], x[2], x[3],.........x[n] The
subscript can begin with number 0. That is x[0] is allowed. Now we will discuss the properties of
arrays and work with 1-D Arrays before we go on to discuss 2-D and multidimensional arrays.
Properties of Array
● Each element of an array is of the 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.
Declaration of Array
We can declare an array in the c language in the following way.
data_type array_name[array_size];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
In such a case, there is no requirement to define the size. So it may also be written as the
following code.
int marks[]={20,30,40,50,60};
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of
array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Run Time Initialization
An array can be explicitly initialized at run time. This approach is usually applied for initializing
large arrays. For example, consider the following segment of a C program.
– – – –– – – –
– – – –– – – –
for (i = 0; i < 100; i = i+1)
{
if i < 50
sum[i] = 0.0; /* assignment statement */
else
sum[i] = 1.0;
}
– – – –– – – –
– – – –– – – –
The first 50 elements of the array sum are initialized to zero while the remaining 50 elements
are initialized to 1.0 at run time.
We can also use a read function such as scanf to initialize an array. For example, the
statements
int x [3];
scanf(“%d%d%d”, &x[0], &x[1], &x[2]);
will initialize array elements with the values entered through the keyboard.
#include <stdio.h>
int main() {
int n, i;
float num[100], sum = 0.0, avg;
avg = sum / n;
printf("Average = %.2f", avg);
return 0;
}
Program to Find Largest Element in an Array:
#include <stdio.h>
int main() {
int n;
double arr[100];
printf("Enter the number of elements (1 to 100): ");
scanf("%d", &n);
return 0;
}
2D array
A two-dimensional array can be thought of as a rectangular display of elements with rows and
columns. For example, elements of int x[3][3] are shown below:
Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces. For example,
int table[2][3] = { 0,0,0,1,1,1};
initializes the elements of the first row to zero and the second row to one. 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.
We can also initialize a two-dimensional array in the form of a matrix as shown below:
int table[2][3] = {
{0,0,0},
{1,1,1}
};
Note the syntax of the above statements. Commas are required after each brace that closes off
a row, except in the case of the last row.
When the array is completely initialized with all values, explicitly, we need not specify the size of
the first dimension. That is, the statement
int table [ ] [3] = {
{ 0, 0, 0},
{ 1, 1, 1}
};
is permitted.
If the values are missing in an initializer, they are automatically set to zero. For instance, the
statement:
int table[2][3] = {
{1,1},
{2}
};
will initialize the first two elements of the first row to one, the first element of the second row to
two, and all other elements to zero.
When all the elements are to be initialized to zero, the following short-cut method may be used.
int m[3][5] = { {0}, {0}, {0}};
The first element of each row is explicitly initialized to zero while other elements are
automatically initialized to zero. The following statement will also achieve the same result:
int m [3] [5] = { 0, 0};
int main()
{
int marks[5][2];
int i,j;
for(i=0;i<5;i++){
for(j=0;j<2;j++){
printf("\nEnter the value for [%d][%d]",i,j);
scanf("%d",&marks[i][j]);
}
}
for(i=0;i<5;i++){
for(j=0;j<2;j++){
printf("\t%d",marks[i][j]);
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main()
{
int m, n, largest, smallest;
int largrowloc, largcolumnloc, smallrowloc, smallcolumnloc;
if(smallest>arr[i][j])
{
smallest=arr[i][j];
smallrowloc=i; //row location of smallest element
smallcolumnloc=j; //column location of smallest element
}
}
}
// display results
printf("\n"); // new line
printf("Largest element in array is %d in location arr[%d][%d]\n",
largest, largrowloc, largcolumnloc);
printf("Smallest element in array is %d in location arr[%d][%d]\n",
smallest, smallrowloc, smallcolumnloc);
return 0;
}
Program to check whether a 3x3 Matrix is symmetric matrix
#include <stdio.h>
int main()
{
int A[3][3]; // Original matrix
int B[3][3]; // Transpose matrix
/*
* Find transpose of matrix A
*/
for(row=0; row<3; row++)
{
for(col=0; col<3; col++)
{
/* Store each row of matrix A to each column of matrix B */
B[row][col] = A[col][row];
}
}
/*
* Check whether matrix A is equal to its transpose or not
*/
isSymmetric = 1;
for(row=0; row<3 && isSymmetric; row++)
{
for(col=0; col<3; col++)
{
/* If matrix A is not equal to its transpose */
if(A[row][col] != B[row][col])
{
isSymmetric = 0;
break;
}
}
}
/*
* If the given matrix is symmetric.
*/
if(isSymmetric == 1)
{
printf("\nThe given matrix is Symmetric matrix: \n");
printf("\n");
}
}
else
{
printf("\nThe given matrix is not Symmetric matrix.");
}
return 0;
}
Strings and Character Array
String is a sequence of characters that are treated as a single data item and terminated by a
null character '\0'. Remember that the C language does not support strings as a data type. A
string is actually a one-dimensional array of characters in C language. These are often used to
create meaningful and readable programs.
Declaration of strings:
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax
for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used to define
the length of the string, i.e the number of characters strings will store. Please keep in mind that
there is an extra terminating character which is the Null character (‘\0’) used to indicate the
termination of string which differs strings from normal character arrays.
Initializing a String:
A string can be initialized in different ways. We will explain this with the help of an example.
Below is an example to declare a string with name as str and initialize it with "c string"
1. char str[] = "c string";
2. char str[50] = "c string";
3. char str[] = {'c',' ','s','t','r','i','n','g','\0'};
4. char str[14] = {'c',' ','s','t','r','i','n','g','\0'};
When the compiler encounters a sequence of characters enclosed in the double quotation
marks, it appends a null character \0 at the end by default.
What if the length of the string is more than the size of the character array?
The scanf() function reads the sequence of characters until it encounters whitespace (space,
newline, tab, etc.).
notice that we have used the code name instead of &name with scanf().
scanf("%s", name);
This is because the name is a char array, and we know that array names decay to pointers in C.
Thus, the name in scanf() already points to the address of the first element in the string, which is
why we don't need to use &.
● But scanf() function terminates its input on the first white space it encounters.
● The fgets() function can also be used to read character string with white spaces
The following are the most commonly used string handling functions.
Method Description
You can use the gets() and fgets() function to read a line of string. And, you can use puts() to
display the string.
But gets() is deprecated, we can also use fgets()
fgets() vs gets(): fgets() is safer
fgets() reads a line from the specified stream and stores it into the string pointed to by str. It
stops when either (n-1) characters are read, the newline character is read, or the end-of-file is
reached, whichever comes first.
Syntax :
Suppose we have a character array of 15 characters and input is greater than 15 characters,
gets() will read all these characters and store them into variable.Since, gets() do not check the
maximum limit of input characters, so at any time compiler may return buffer overflow error.
#include <stdio.h>
int main(void)
{
char str[15];
return 0;
}
That is why gets() is dangerous to use, it does not check the array bounds, while fgets() is safer,
because it checks the array bound. It keeps on reading until a new line character is encountered
or the maximum limit of the character array.
Display Of Strings With Different Formats
The printf() function is used for displaying the various data types. The printf() function with %s
format specifier is to be used for displaying the string on the screen. Various formats are shown
in the code below:
#include <stdio.h>
int main()
{
char text[15]= "Hello World";
printf("%s\n",text);
printf("%.5s\n",text);
printf("%.8s\n",text);
printf("%.11s\n",text);
printf("%-10.4s\n",text);
return 0;
}
Let us understand the statements we used in the code , numbered below:
1. printf("%s\n",text);
2. printf("%.5s\n",text);
3. printf("%.8s\n",text);
4. printf("%.11s\n",text);
5. printf("%-10.4s\n",text);
1. The 1st statement displays the output ‘Hello World’. The entire string can be displayed with
the first statement.
2. We can also specify the precision with a format string. The precision (number of characters to
be displayed) is provided after the decimal point. Consider the 2nd statement in the above table
(the first five characters are displayed). Here the integer value 5 on the right side of the decimal
point specifies the five characters to be displayed.
3. In the 3rd statement, the first eight characters are displayed, while statement 4 displays the
entire string.
4. The 5th statement with—sign (% – 10.4s ), displays the string with left justified.
When the field length is less than the length of the string, the entire string is printed. When it is
greater than the length of the string, blank spaces are initially printed followed by the string.
Additionally, when the number of characters to be displayed is specified as zero after the
decimal point, nothing will be displayed.
Another Example:
Puts function in C
The puts function in C is used to write a line or string to the output stream (stdout) that is up to,
but does not include, the null character. The puts function also appends a newline character to
the output and returns an integer.
The puts function takes a single mandatory parameter, i.e., a null-terminated character array.
The puts function writes the provided argument to the output stream and appends a newline
character at the end. If the execution is successful, the function returns a non-negative integer;
otherwise, it returns an EOF (End-of-File) for any error.
#include <stdio.h>
#include <string.h>
int main() {
// initializing strings
char str1[] = "Hello World";
char str2[] = "Using puts in C";
// writing to stdout
puts(str1);
puts(str2);
return 0;
}
String Functions:
strlen(): The strlen() function returns the length of the given string. It doesn't count null
character '\0'.
strcpy(): The strcpy(destination, source) function copies the source string in destination.
strcat(): The strcat(first_string, second_string) function concatenates two strings and the result
is returned to first_string.
We must ensure that the size of the first_string (to which the second string is appended) is
large enough to accommodate the final string (to avoid absurd results).
strcmp(): The strcmp(first_string, second_string) function compares two string and returns 0 if
both strings are equal.
strrev(): The strrev(string) function returns the reverse of the given string. Let's see a simple
example of strrev() function.