BIT104 SLM Library - SLM - Unit 06
BIT104 SLM Library - SLM - Unit 06
Structure:
6.1 Introduction
Objectives
6.2 One Dimensional Arrays
6.3 Multidimensional Arrays
6.4 Strings
Reading and Writing Strings
Manipulating Strings with string.h Library
6.5 Summary
6.6 Terminal Questions
6.7 Answers
6.8 Exercises
6.1 Introduction
In the previous unit, we discussed the various branching and looping
statements available in C language. We learned how conditional and
unconditional branching statements can alter the flow of program sequence.
We also discussed looping statement to repeat statement or set of
statements which is executed over and over again until the condition for
termination of loop are satisfied. We learned how to break the current
iteration and continue with next iteration of loop. In this unit, we will discuss
arrays and strings. We will learn how arrays and strings are formed and
manipulated.
Many applications require processing of multiple data items that have
common characteristics such as a set of numeric data or character data, for
example daily weather information or test result of subjects of students. In
such situations it is always convenient to place the data items into an array,
where they will share the same name. An array is a collection of similar type
of elements. All elements in the array are referred with the array name.
Since arrays hold a group of similar data, it is very easy to perform looping
and arithmetic operations on a group of data.
We can use array for a simple list of data in a one dimensional array or a
table of data in two or multidimensional arrays. This chapter covers the
processing of both one-dimensional and multidimensional arrays.
Objectives:
After studying this unit, you should be able to:
declare, initialize and process one-dimensional and multi-dimensional
arrays
explain about strings and how to process them
describe the library functions available in C to process strings
write programs using I/O functions to handle strings
To set all the elements of an array to some value, we must do it one by one,
as in the loop example above.
To copy the contents of one array to another, we must again do so one by
one:
int b[10];
for(i = 0; i < 10; i = i + 1)
b[i] = a[i];
We can neither set all elements of an array at once nor assign one array to
another. Both the assignments
a = 0; /* WRONG */
and
int b[10];
b = a; /* WRONG */
are illegal.
In the above example, we simple declare an array with 10 elements and
loop over all 10 elements. However, we can use an array that is bigger than
actually needed, and use a second variable to keep track of how many
elements of the array that are currently in use. For example, we might have
an integer variable
int no; /* number of elements of a[] in use */
Then, when we want to do something with a (such as print it out), the loop
would run from 0 to no, not 10 (or whatever a's size was):
for(i = 0; i < no; i = i + 1)
printf("%d\n", a[i]);
Naturally, we would have to make sure that the no's value was always less
than or equal to the number of elements actually declared in a.
Size of an Array: As mentioned earlier, an array consists of consecutive
memory locations. Consider the array declared like,
data-type myArray[Size];
We can calculate the total bytes of an array using the following expression:
sizeof(myArray)
myArray is the name of the array.
or we can use following expression to calculate the total bytes of the array
sizeof(data-type) * Size
Here data-type is the data type of the array; Size specifies the total number
of elements the array can take. This expression evaluates to the total
number of bytes the array takes.
Example Program for the Array:
Here is a slightly larger example of the use of arrays. Suppose we want to
investigate the behavior of rolling a pair of dice. The total roll can be
anywhere from 2 to 12, and we want to count result of each roll. We will use
an array to keep track of the counts: a[2] will count how many times we
have rolled 2, and so on.
We will simulate the roll of a dice by calling C's random number generation
function, rand(). Each time we call rand(), it returns a different, pseudo-
random integer. The values that rand() returns typically span a large range,
so we will use C's modulus (or “remainder'') operator % to produce random
numbers in the range we want. The expression rand() % 6 produces
random numbers in the range 0 to 5, and rand() % 6 + 1 produces random
numbers in the range 1 to 6.
Program 6.1: Program to simulate the roll of a dice
#include <stdio.h>
#include <stdlib.h>
main()
{
int i;
int d1, d2;
int a[13]; /* uses [2..12] */
return 0;
}
We include the header <stdlib.h> because it contains the necessary
declarations for the rand() function. We declare the array of size 13 so that
its highest element will be a[12]. (We are wasting a[0] and a[1]; this is no
great loss.) The variables d1 and d2 contain the rolls of the two individual
dice and we add them together to decide which cell of the array to
increment, in the line
a[d1 + d2] = a[d1 + d2] + 1;
After 100 rolls, we print the array out. Typically, we will see mostly 7's, and
relatively few 2's and 12's.
Self-Assessment Questions
1. In C, an array subscript starts from __________.
2. Will there be a compilation error for the following program segment?
(Yes/No)
int a[5] = {1, 2, 3, 4, 5};
int b[5] = {5, 4, 3, 2, 1};
int c[5][5];
…
c=a+b;
…
0 4 5 6
1 1 5 6
2 0 4 4
Note: array1[0][0] contains the value 4. array1 [0][1] contains the value 5.
array1 [0][2] contains value 6. array1 [1][0] contains the value 1. array1[1][1]
contains the value 5. Similarly we can find the value of array1[1][2] to
array1[2][2].
We can access arrays like:
Array1[1][4]= -2;
printf ("Element [2][1] is %d", array1[2][1]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &b[i][j]);
/* Add the matrices */
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j] = a[i][j]+b[i][j];
/* Print the sum */
printf(“The sum of matrices:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(“%d\t”, c[i][j]);
printf(“\n”);
}
}
First, it will be asked to enter the order of matrix (number of rows and
columns) and then two matrices. For example if the user entered order as 2,
2 i.e. two rows and two columns and matrices as
First Matrix a:
12
34
Second matrix b:
45
-1 5
then output matrix c (sum of First and Second matrix) will be
57
29
Multidimensional arrays are processed in the same manner as one-
dimensional arrays, on an element-by-element basis.
Self Assessment Questions
3. In a two-dimensional matrix, the first subscript in the declaration
specifies number of ________________.
6.4 Strings
A string is a sequence of characters. String literals are words surrounded by
double quotation marks. For example:
“C String”
In C, strings are represented by arrays of characters with the end of the
string marked with a special character, the null character. The null or string-
terminating character is represented by another character escape sequence,
\0. So, to declare a string 8 character, we have to reserve space of 9
character (that is eight character + one null character).
The following declaration and initialization create a string consisting of the
word "Program". To hold the null character at the end of the array, the size
of the character array containing the string is one more than the number of
characters in the word "Program".
char greeting[8] = {'P', 'r', 'o', 'g', 'r', ’a’, 'm', '\0'};
Whenever we write a string, enclosed in double quotes, C automatically
creates an array of characters for us, containing that string, terminated by
the \0 character. We can write the above statement as follows:
char greeting[] = "Program";
In this case, we can leave out the dimension of the array, since the compiler
can compute it for us based on the size of the initializer (8, including the
terminating \0). This is the only case where the compiler sizes a string array
for us, however; in other cases, it will be necessary that we decide how big
the arrays and other data structures we used to hold the string.
Difference between String, Characters and Integer Data Types:
When working with strings, it is important to keep in mind the differences
between characters and strings. We must also remember the way
characters are represented, and about the relation between character
values and integers.
As we know, a character is represented internally as a small integer, with a
value depending on the character set in use. For example, we might find
that 'A' had the value 65, that 'a' had the value 97 and that '+' had the value
43.
There is a big difference between a character and a string: string always
ends null character, even a string which contains only one character (other
than the \0). For example, 'a' is not the same as "a".
If we have a string:
char string[ ] = "hello!";
We can modify its first character by saying
string[0] = 'H';
We can modify any character in the string in this way. Since we are
replacing a character, we want a character constant, 'H'. It would not be
right to write
string[0] = "H"; /* WRONG */
because "H" is a string (an array of characters), not a single character. (The
destination of the assignment, string [0], is a char, but the right-hand side is
a string; these types don't match.)
On the other hand, when we need a string, we must use a string. To print a
single newline, we could call
printf("\n");
It would not be correct to call
printf('\n'); /* WRONG */
printf always wants a string as its first argument. (As one final example,
putchar wants a single character, so putchar('\n') would be correct, and
putchar("\n") would be incorrect.)
There is difference between strings and integers. So when we write
character '1' as an integer in the following manner:
int i = '1';
The value of the character '1' is in the machine's character set. Character
data is represented in a computer by using standardized numeric codes
called the American Standard Code for Information Interchange (ASCII).
The ASCII code associates an integer value for each symbol in the
depicts the first method, which fetches each individual element, array_ch[i],
consecutively in a loop, and prints out one character next to another by
using the character format specifier %c in the printf() call. Whenever we are
dealing with a character array, as was mentioned earlier, the null character
‘\0’ signals the end of the string (even though it may not yet be the end of
the array). It is a good idea to watch for the null character so we know when
to stop printing, so the conditional expression of for loop terminate the for
loop if the current element is a null character.
The second method is simpler. We simply tell the printf() function where to
find the first element the array (the address of its first element). Also, we
need to use the string format specifier %s in the printf() call as shown line
below:
printf( “%s\n”, array_ch);
Note that the array_ch contains the address of the first element in the
array—that is, the starting address of the array. The %s format specifier
tells printf() to keep printing characters until it finds a null character just as
we did, ourselves, in the first method.
We can read string using scanf() function from the standard input stream.
Using the string format specifier %s tells the scanf() function to continue
reading characters until a space, a newline, a tab, a vertical tab, or a form
feed is encountered. Characters read by the scanf() function are stored into
an array referenced by the corresponding argument. The array should be
big enough to store the input characters. A null character is automatically
appended to the array after the string is read.
Example: following is the example code for reading and writing string using
printf and scanf function.
char str[80];
printf(“Enter a string:\n”);
scanf(“%s”, str);
printf(“Here are what We’ve entered:\n”);
printf(“\n%s”, str);
#include<stdio.h>
main()
{
char line[80];
gets(line);
puts(line);
}
This program uses gets() and puts() functions rather than scanf() and printf(),
to transfer the line of text into and out of the computer.
6.4.2 Manipulating strings with string.h Library
The C library contains a few basic string manipulation functions defined in
string.h file. We will discuss how these functions might be used and
implemented. We need to include string.h header file in our program in
order to use the function defined in string.h using following line:
#include <string.h>
The more commonly used functions along with their purpose are listed in
table 6.2:
Table 6.2: List of commonly used string.h functions
Function Purpose
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of another
strcpy Copies a string into another
strncpy Copies first n characters of one string into another
strcmp Compares two strings
strncmp Compares first n characters of two strings
strcmpi Compares two strings without regard to case ("i" denotes
that this function ignores case)
strdup Duplicates a string
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string
strset Sets all characters of string to a given character
strnset Sets first n characters of a string to a given character
strrev Reverses string
We will discuss only a few functions form the above list in this unit.
Comparing string – strcmp():
strcmp(s1, s2); // Returns 0 if string s1 and string s2 are the same; less
than 0 if s1<s2; greater than 0 if s1>s2.
This is a function which compares two strings to find out whether they are
same or different. The two strings are compared character by character until
there is a mismatch or the end of one of the strings is reached, whichever
occurs first. The standard library's strcmp function returns 0 if two string are
If we want to copy a string from one array to another, we can copy each
item of the first array to the corresponding element in the second array, or
we can simply call the C function strcpy() to do the job for We.
Example: Here is an example - use of strcpy():
#include <string.h>
char string1[ ] = "Hello, world!";
char string2[20];
strcpy(string2, string1);
The destination string is strcpy's first argument, so that a call to strcpy
mimics an assignment expression (with the destination on the left-hand
side). Notice that we had to allocate string2 big enough to hold the string
that would be copied to it.
Length of string – strlen():
strlen(s1); Returns the length of string s1
In C, we can use a function called strlen() to measure the length of a string.
The strlen function returns the length of the string (i.e. the number of
characters in it), not including the \0.
Example: Here is an example use of strlen():
char string7[ ] = "abc";
int len = strlen(string7);
printf("%d\n", len);
Since a string is just an array of characters, all of the string-handling
functions we have just seen can be written quite simply, using techniques
no more complicated than the ones we already know.
We can implement above functions. We are going to discuss how these
functions might be implemented.
Here is a simple version of strcpy:
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}
The above code of strcpy work as: In while loop, it looks at characters in the
src string one at a time, and assigns them, one by one, to the corresponding
positions in the dest string as long as src character is not \0. When it is done,
it terminates the dest string by appending a \0. (After exiting the while loop, i
is guaranteed to have a value one greater than the subscript of the last
character in src.)
We can write above code of strcpy using for loop as:
while(1)
{
if(str1[i] != str2[i])
return str1[i] - str2[i];
if(str1[i] == '\0' || str2[i] == '\0')
return 0;
i++;
}
}
Above code for strcmp work as: In while loop, characters are compared one
at a time. If two characters in one position differ, the strings are different,
and it returns a value less than zero if the first string (str1) is alphabetically
less than the second string. The expression str1[i] - str2[i] will yield a
negative result if the i'th character of str1 is less than the corresponding
character in str2, characters in C are represented by their numeric character
set values
The above code of strlen work as: In this case, we have to do is find the ‘\0’
that terminates the string, and it turns out that the three control expressions
of the for loop do all the work; there's nothing left to do in the body.
Therefore, we use an empty pair of braces { } as the loop body. Equivalently,
we could use a null statement, which is simply a semicolon:
6.5 Summary
Let us recapitulate important points discussed in this unit:
An array is a variable that can hold more than one value of same data
type. In C, arrays are zero-based.
The C language allows arrays of any dimension to be defined.
6.7 Answers
Self-Assessment Questions
1. 0
2. Yes
3. rows
4. true
5. Compilation error
6. strcpy
7. false
Terminal Questions
1. #include<stdio.h>
main()
{
int i=0, sum=0, x;
printf(‘Enter a number:”);
scanf(“%d”, &x);
while(i<10)
{
sum+=x*x;
i++;
}
printf(“Sum=%d”, sum);
}
2. 60
3. Yes, It is correct.
4. String can be read and write using the scanf() and printf function
respectively by using %s format specifiers. (Refer section 6.4.1 for more
information.)
5. // Program to store and process score of golf player using arrays
#include <stdio.h>
int main(void)
{
int SIZE = 10;
int index, score[SIZE];
int sum = 0;
float average;
printf("Enter %d golf scores:\n", SIZE);
for (index = 0; index < SIZE; index++)
scanf("%d", &score[index]); */read in the ten scores
printf("The scores read in are as follows:\n");
for (index = 0; index < SIZE; index++)
printf("%5d", score[index]); */verify input
printf("\n");
for (index = 0; index < SIZE; index++)
6.8 Exercises
1. Write a program to count the number of vowels and consonants in a
given string.
2. Write a program to arrange a list of numbers in ascending order.
3. Write a program to multiply two matrices.
4. Write a program to rewrite a given string in the alphabetical order.
5. Write a program to transpose a given matrix.