0% found this document useful (0 votes)
39 views22 pages

BIT104 SLM Library - SLM - Unit 06

Uploaded by

pavanmay227597
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)
39 views22 pages

BIT104 SLM Library - SLM - Unit 06

Uploaded by

pavanmay227597
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/ 22

Principles of C Programming Unit 6

Unit 6 Arrays and Strings

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.

Sikkim Manipal University B2074 Page No.: 126


Principles of C Programming Unit 6

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

6.2 One Dimensional Arrays


An array is a collection of values of the same type that are referred to
through a common name. In C, array elements are stored in consecutive
memory locations, each of which can store the same data type and which
can be references through the same variable name. In other words, an array
is a variable that can hold more than one value of same data type.
Arrays can be declared of int, char or double or any other type. Arrays must
be declared before they can be used in the program. Standard array
declaration is as:
type variable_name[size];
Here type specifies the variable type of the element which is going to be
stored in the array and size defines how many elements the array will hold.
For example
int a[10];
declares an array, named a, consisting of ten elements, each of type int.
Indexing Arrays: An element is accessed by indexing the array name.
This is done by placing the index of the element within square brackets after
the name of the array. We specify which of the several values we are
referring to at any given time by using a numeric subscript (index). (Arrays
in programming are similar to vectors or matrices in mathematics.) We can
represent the array as stated above with the picture specified below:
a:
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

Sikkim Manipal University B2074 Page No.: 127


Principles of C Programming Unit 6

In C, arrays are zero-based, the ten elements of a 10-element array are


numbered from 0 to 9. The subscript which specifies a single element of an
array is simply an integer expression in square brackets. The first element
of the array is a[0], the second element is a[1], and so on. It must be noted
that there is no element a[10]; the topmost element is a[9].
We can use these “array subscript expressions'' anywhere, for example:
a[0] = 10;
a[1] = 20;
a[2] = a[0] + a[1];
Note that the subscripted array references (i.e. expressions such as a[0]
and a[1]) can appear on either side of the assignment operator.
Initializing Arrays: Initializing of array is simple in C programming. The
initializing values are enclosed within the curly braces in the declaration and
placed following an equal sign after the array name. Here is an example
which declares and initializes an array of five elements of type int. Array can
also be initialized after declaration. Look at the following C code which
demonstrates the declaration and initialization of an array.
int myArray[5] = {1, 2, 3, 4, 5}; //declare and initialize the array in one
statement
OR
int myArray[5];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;
myArray[3]=4;
myArray[4]=5;
The subscript does not have to be a constant like 0 or 1; it can be any
integral expression. For example, it is common to loop over all elements of
an array:
int i;
for(i = 0; i < 10; i = i + 1)
a[i] = 0;
This loop sets all ten elements of the array a to 0.

Sikkim Manipal University B2074 Page No.: 128


Principles of C Programming Unit 6

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.

Sikkim Manipal University B2074 Page No.: 129


Principles of C Programming Unit 6

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] */

for(i = 2; i <= 12; i = i + 1)


a[i] = 0;

for(i = 0; i < 100; i = i + 1)


{
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
a[d1 + d2] = a[d1 + d2] + 1;

Sikkim Manipal University B2074 Page No.: 130


Principles of C Programming Unit 6

for(i = 2; i <= 12; i = i + 1)


printf("%d: %d\n", i, a[i]);

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;

6.3 Multidimensional Arrays


In addition to one-dimensional arrays, the C language also supports
multidimensional arrays.
Declaration and Initialization:
We can declare arrays with as many dimensions as the compiler allows.
The general form of declaring a multidimensional array is:
data-type Array-Name[Size1][Size2]. . . [SizeN];
where N can be any positive integer.

Sikkim Manipal University B2074 Page No.: 131


Principles of C Programming Unit 6

Because the two-dimensional array, which is widely used, is the simplest


form of the multidimensional array, let us focus on two-dimensional arrays in
this section. A two-dimensional array is considered as an array of one-
dimensional arrays. Matrix is the one of the most used applications for a
two-dimensional array. In C, the two-dimensional matrix can be declared as
follows:
int array1[3][3];
We can declare as well as initialize two-dimensional arrays as follows:
int array1[3][3] = {
{4,5,6 },
{1,5,6},
{0,4,4}
};
or as
int array1[3][3] = { 4,5,6,1,5,6,0,4,4} ; //less readable than above.
It is important to remember that while initializing a two-dimension array, it is
necessary to mention the second (column) dimension, whereas the first
dimension (row) is optional.
Thus the declarations,
int array1[2][3] = { 12, 34, 23, 45, 56, 45 } ;
int array1[ ][3] = { 12, 34, 23, 45, 56, 45 } ;
are perfectly acceptable,
whereas,
int array2[2][ ] = { 12, 34, 23, 45, 56, 45 } ;
int array2[ ][ ] = { 12, 34, 23, 45, 56, 45 } ;
will never work.
Accessing two-dimensional Arrays:
It must be noted that like ordinary arrays, two-dimensional arrays are
numbered from 0. Therefore, the array1 declared above has elements from
array1[0][0] to array1[2][2]. Two-dimensional arrays have rows and columns.
Table 6.1 is an illustration of the above mentioned array in matrix form:

Sikkim Manipal University B2074 Page No.: 132


Principles of C Programming Unit 6

Table 6.1: matrix representation of array1[3][3]


Col-> 0 1 2
Row
|
V

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]);

Program 6.2: Program to add two matrices


#include <stdio.h>
main()
{
int a[5][5], b[5][5], c[5][5];
int i, j, m, n;
// enter the number of rows and column for matrix
printf(“Enter the order of the matrices (equal to or less than 5):”);
scanf(“%d%d”, &m, &n);

//Reading first matrix a’s elements


printf(“Enter the elements of A matrix:\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &a[i][j]);

// Reading second matrix b’s elements


printf(“Enter the elements of B matrix:\n”);

Sikkim Manipal University B2074 Page No.: 133


Principles of C Programming Unit 6

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 ________________.

Sikkim Manipal University B2074 Page No.: 134


Principles of C Programming Unit 6

4. A two-dimensional array is considered as an array of one-dimensional


arrays. (True/False)

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

Sikkim Manipal University B2074 Page No.: 135


Principles of C Programming Unit 6

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

Sikkim Manipal University B2074 Page No.: 136


Principles of C Programming Unit 6

character set, such as letters, digits, punctuation marks, special characters,


and control characters. In ASCII code for ‘1’ is 49, which is assigned to i, not
integer value 1.
To find the numeric value of a digit character (or to go the other way, to get
the digit character with a particular value) we can make use of the fact that,
in any character set used by C, the values for the digit characters, whatever
they are, are contiguous. In other words, no matter what values '0' and '1'
have, '1' - '0' will be 1 (and, obviously, '0' - '0' will be 0). So, for a variable c
holding some digit character, the expression
c - '0'
gives us its value. (Similarly, for an integer value i, i + '0' gives us the
corresponding digit character, as long as 0 <= i <= 9.)
Just as the character '1' is not the integer 1, the string "123" is not the
integer 123. When we have a string of digits, we can convert it to the
corresponding integer by calling the standard function atoi:
char string[] = "123";
int i = atoi(string);
int j = atoi("456");
6.4.1 Reading and Writing strings
The scanf and printf functions:
String can be read and write using the scanf() and printf() function
respectively.
There are two ways to display this array: display all the characters
individually, or treat them as a character string. Both methods are
demonstrated in the following program.
Program 6.3: Printing an Array of Characters
#include <stdio.h>
main()
{
char array_ch[7] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘!’, ‘\0’};
int i;
// print using for loop
for (i=0; array_ch[i] != ‘\0’ && i<7; i++)
printf(“%c”, array_ch[i]);

Sikkim Manipal University B2074 Page No.: 137


Principles of C Programming Unit 6

// print using printf function


printf( “%s\n”, array_ch);
return 0;
}
In this program, a character array, array_ch, is declared and initialized.
Lines:
for (i=0; array_ch[i] != ‘\0’ && i<7; i++)
printf(“%c”, array_ch[i]);

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.

Sikkim Manipal University B2074 Page No.: 138


Principles of C Programming Unit 6

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);

The gets() and puts() Functions:


The gets() and puts() functions facilitate the transfer of strings between the
computer and the standard input/output devices. Each of these functions
accepts a single argument. The argument must be a data item that
represents a string (an array of characters). The string may include
whitespace characters. In the case of gets(), the string will be entered from
the keyboard, and will terminate with a newline character (that is a string
will end when the user presses the RETURN key). The gets function adds a
null character to the end of the string.
The puts() function sends all characters of string, except the null character,
to the stdout, and appends a newline character to the output.
Program 6.4: Reading and writing a line of text using gets() and puts().

#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:

Sikkim Manipal University B2074 Page No.: 139


Principles of C Programming Unit 6

#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

Sikkim Manipal University B2074 Page No.: 140


Principles of C Programming Unit 6

identical, or a negative number if the first string is alphabetically “less than''


the second string, or a positive number if the first string is “greater.''
Example: Here is an example use of strcmp():
char string3[] = "this is";
char string4[] = "a test";
if(strcmp(string3, string4) == 0)
printf("strings are equal\n");
else printf("strings are different\n");
This code fragment will print “strings are different''.
Concatenate strings- strcat :
strcat(s1, s2); Concatenates string s2 onto the end of string s1
The strcat function appends a copy of the string pointed to by s2 to the end
of the string pointed to by s1. It returns a pointer to s1 where the resulting
concatenated string resides.
In strcat function, the terminating null character in destination is overwritten
by the first character of source, and a null-character is included at the end of
the new string formed by the concatenation of both in destination.
Example: Here is an example use of strcat():
char string5[20] = "Hello, ";
char string6[] = "world!";
printf("%s\n", string5);
strcat(string5, string6);
printf("%s\n", string5);
The first call to printf prints “Hello, '', and the second one prints “Hello,
world!'', indicating that the contents of string6 have been tacked on to the
end of string5. Notice that we declared string5 with extra space, to make
room for the appended characters.
If we have a string and we want to know its length (perhaps so that we can
check whether it will fit in some other array we have allocated for it), we can
call strlen, as discussed below.
Coping String- strcpy():
strcpy(s1, s2); // Copies string s2 into string s1

Sikkim Manipal University B2074 Page No.: 141


Principles of C Programming Unit 6

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:

mystrcpy(char dest[ ], char src[ ])


{
int i = 0;
while(src[i] != '\0')
{

Sikkim Manipal University B2074 Page No.: 142


Principles of C Programming Unit 6

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:

for(i = 0; src[i] != '\0'; i++)


dest[i] = src[i];
dest[i] = '\0';

Code for simple version of strcmp is as follows :


mystrcmp(char str1[ ], char str2[ ])
{
int i = 0;

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

Sikkim Manipal University B2074 Page No.: 143


Principles of C Programming Unit 6

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

Finally, here is a version of code for simple strlen:


int mystrlen(char str[ ])
{
int i;
for(i = 0; str[i] != '\0'; i++)
{}
return i;
}

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:

for(i = 0; str[i] != '\0'; i++) ;

Self Assessment Questions


5. Will there be a compilation error for the following program? (Yes/No).
char str1[10];
str1=”Hello, world”;
printf(“%s”, str1);
6. The library function used to copy one string to another is
_________________.
7. The library function atoi can be used for any string. (True/False)

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.

Sikkim Manipal University B2074 Page No.: 144


Principles of C Programming Unit 6

 In C, strings are represented by arrays of characters with the end of the


string is marked with a special character, the null character.
 The C library string.h contains a basic string manipulation functions like
strcmp , strcat and so on.
 The puts() function sends all characters of string, except the null
character, to the stdout, and appends a newline character to the output.
 The gets() function can be used to read a series of characters. This
function stops reading when the newline character is encountered that is
return key is pressed. The function adds a null character to the end of
the string.

6.6 Terminal Questions


1. Write a program for 10 times summation of square of a number.
2. How many elements can the array in the following declaration
accommodate? int a[3][4][5];
3. Is the following array declaration and initialization correct?
int a[2][2]={1,2,3,4};
4. Explain reading and writing of strings.
5. Write a Program to do the following:
1. Store golf score of player for ten matches.
2. Prints the score.
3. Calculate the average of score and display it.

6.7 Answers
Self-Assessment Questions
1. 0
2. Yes
3. rows
4. true
5. Compilation error
6. strcpy
7. false

Sikkim Manipal University B2074 Page No.: 145


Principles of C Programming Unit 6

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++)

Sikkim Manipal University B2074 Page No.: 146


Principles of C Programming Unit 6

sum += score[index]; */add them up


average = (float) sum / SIZE; */ time-honored method
printf("Sum of scores = % d,average = %.2f\n", sum, average);
return 0;
}

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.

Reference and further reading:


1. Balaguruswami, “Programming In Ansi C 5E” Tata McGraw-Hill
2. Ajay Mittal (2010), “Programming In C: A Practical Approach”, Published
by Pearson education.

Sikkim Manipal University B2074 Page No.: 147

You might also like