Showing posts with label 'ARRAYS' in C LANGUAGE. Show all posts
Showing posts with label 'ARRAYS' in C LANGUAGE. Show all posts

Wednesday, October 27, 2010

'ARRAYS' in C LANGUAGE



'ARRAYS' in C LANGUAGE


'ARRAYS' in C LANGUAGE

HIGH-LEVEL LANGUAGES

So far, it has been necessary to know how many items are to be stored and to declare a variable for each item. Further more, if a large amount of data is to be stored, would be a long and tedious task to think of a separate variable name for each data, and then to type the declaration for each one of these variables.

Arrays are the solution to this problem. They are such an important part of the art of programming that they are included in every

What is an Array?
In C, as in other computer languages, it is possible to assign a single name to a whole group of similar data. For example, if we are interested in a large number of recorded Celsius temperature, we can assign a common name such as C_temp to all of the data. Then we can refer to each element in terms of its position within the list of items. This is done in mathematics, as well as in computer programming, using an entity called an array.

An array is a group of elements that share a common name and that are differentiated from one another by their positions within the array. For example, if we have five numbers, all of which are named x, they may be listed:

X
58
63
49
18
7

The position of each of these elements can be indicated by means of a subscript:

X1 = 58
X2 = 63
X3 = 49
X4 = 18
X5 = 7

In mathematics, a subscript is a number written to the right of the variable name, slightly below the line, and usually in small type. The subscript indicates the position of the particular element with respect to the rest of the elements.

For those movie buffs who are fans of the old Charlie Chan detective movies, you will remember that whenever it became necessary for Mr. Chan to introduce his sons to clients, he would always introduce them as: “This is my number one son…my number two son….” Etc. It is clear from this that even though computers were made, Mr. Chan actually resorted to the method of introducing his sons by their subscripts!

Since it is impossible to display subscripted numbers on the standard computer terminal, the usual recourse is to enclose the subscript in parentheses or brackets. In C (as in Pascal), square brackets are used. The following five statements are valid in C.
X[1] = 58;
X[2] = 63;
X[3] = 49;
X[4] = 18;
X[5] = 7;
HOW ARRAYS ARE USEFUL
To see the usefulness of arrays, consider the problem of reading the age of 5 persons, printing them out individually and computing the average. Here is a solution that does not use arrays.

#include
main()
{
int a1, a2, a3, a4, a5;
float sum=0;
printf (“Age:”);
scanf(“%d”, &a1);
sum += a1;
printf (“Age:”);
scanf(“%d”, &a2);
sum += a2;
printf (“Age:”);
scanf(“%d”, &a3);
sum += a3;
printf (“Age:”);
scanf(“%d”, &a4);
sum += a4;
printf (“Age:”);
scanf(“%d”, &a5);
sum += a5;
printf (“The ages that were input are:\n”);
printf(“%d\n”, a1);
printf(“%d\n”, a2);
printf(“%d\n”, a3);
printf(“%d\n”, a4);
printf(“%d\n”, a5);
printf (“Average =%f\n”, sum /5);
}
The program is very simple. It reads the ages of 5 persons, adds them up in a variable called sum, and at the end, divides sum by 5 to get the average age. Needless to say, this is a very clumsy way to write a program. If there are a large number of persons, the number of statements increases proportionately. To avoid this, use a loop. But the problem is that different variables are needed to store the ages of different persons and hence, the loop will have to store and print different variables each time. A more elegant way is to use an array of integers to store the ages, as shown in the example below. Notice the declaration of the array variable in the first line of main().

#include
void main()
{
int age[5]; /* Array of 5 ages, declaration for an array */
int i, n;
float sum = 0;
printf (“Number of persons:”);
scanf(“%d”, &n);
if (n<=0 || n>5)
printf (“Invalid number of persons entered.\n”);
else
{
for (i=0; i {
printf (“Age:”);
scanf(“%d”, &age[i]);
sum += age[i];
}
printf (“the ages input are :\n”);
for (i=0; i printf (“%d\n”, age[i]);
printf (“The average is : %f\n:, sum /n);
} /* end main */
Run
Number of persons: 5
Age: 10
Age: 20
Age: 30
Age: 40
Age: 50
The ages input are:
10
20
30
40
50
The average is : 30.000000

(i) Declaration
The previous program is examined now. Recall that all variables in C must be declared before use. Hence, we must first declare the array. It is done at the beginning of the function main() with the statement
int age[5];

This statement states that age is an array of 5 integers. Note the use of square braces after the array name (i.e., age) enclosing the integer 5 that gives the number of elements in the array. This statement reserves enough memory for age to hold 5 integers. Once the declaration is made, ag [0] refers to the first integer in the array, age [1] refers to the second integer and so on. Finally, age [4] refers to the last integer in the array. In C, array indices always begin with zero. Figure 7.1 shows the declaration of an array.

Fig. 7.1 Array definition

(ii) Accessing array elements
To access a particular element in an array, specify the array name, followed by square braces enclosing an integer, which is called array index. The array index indicates the particular element of the array which we want to access. The numbering of elements starts from zero (i.e. age[0] is the age of the first person). Figure 7.2 depicts the elements of an array in memory. It is assumed that each element of the array (i.e., each integer) occupies two bytes.

Next, observe the loop used to input the elements. It is reproduced here for convenience.

for (i=0; i {
printf (“Age:”);
scanf(“%d”, &age[i]);
sum += age[i];
}

The variable i was from 0 to n-1 (0 to 4 in the above sample run). The function scanf is called to input an integer value. The address of the ith element is passed to scanf. This makes scanf store the integer input into successive integer positions each time the loop is executed. Note that
&age[i];
in the scanf statement refers to the memory location of the integer at the ith position.

The statement
sum+= age[I];
adds the value of the ith integer to sum.

The rest of the program illustrates the use of the array variable in various situations. The first for loop is used to add to the variable sum, and in the second, to print out the values of age that are input.

An element such as age[i] can be used just like any other ordinary integer. Statements such as





Fig 7.2 Elements of the array age

age[i]++; (to increment the value of the ith integer in the array age) and age [i]=11; are perfectly valid.

(iii) Initialization of single dimensional array
Arrays can be initialized once they are declared. The declaration of an array can be done as follows:

int a[5] = { 13, 34, 2, 6, 234 };

Here, a is an array of 5 integers. The initial value of the five integers are specified in order, between the curly braces, separated by commas. The above declaration causes a [0] to be initialized to 13, a[1] to 34 and so on, till a [4], which is initialized to 234. A semicolon always follows the closing brace.

The array size may be omitted during declaration, as shown below.

int a[] = {13, 34, 2, 6, 234};

This declaration is equivalent to the first one. In this case, the subscript is assumed to be equal to the number of elements in the array (5 in this case). Figure 7.3 shows the initialization of an array.

Fig. 7.3 Array Initialization
(iv) Warning
C does not check the validity of the subscript when you use arrays. For example, take a look at the program below:

void main()
{
int a[40];
a[50] = 11;
a[50]++;
}

In essence, the program declares a as an array of 40 integers, and then modifies the 51st element! When you compile the above program, you do not get any error. The executable code is produced. When it is run, the results are unpredictable. Hence, we must be very careful while using array subscripts. A wrong subscript in a large program can cause it to behave erratically, demanding a lot of debugging time.

Similar to an array of integers, we can have an array of any data type. For example, the declaration for an array of 50 floating-point numbers is:
float f[50];
The individual floating-point numbers in this array are accessed as before, i.e., f[0] is the first floating-point number and f(49) the last.

(v) Name of the array
Take the case where f is an array of floating point numbers. It is declared as:

float f[50];

The name of the array is f. If it is used as it is, without any subscript, then it refers to the memory location of the first floating-point number in the array. Recall that placing an ampersand (&) before a variable name refers to its memory location. Thus, the array name f is equivalent to &f[0]. The statement

scanf(“%f”, &f[0]);
is equivalent to
scanf(“%f”, f);

Perhaps, this may not seem to be very useful now. But its potential will be made evident later, in the chapter on pointers.



SUCCESS FOR CAREER





Example 7.1
An example to find out the largest and smallest element in an array is illustrated below:

/* large1.c: largest and smallest element in the vector */
#include
main()
{
int i,n;
float a[50], large, small;
printf (“Size of vector ?”);
scanf (“%d, &n);
printf (“\n Vector elements?\n”);
for (i=0; i scanf (“%f”, &a[i]);

/* Initialization */
large = a[0];
small = a[0];
/* largest and smallest elements */
for (i=l; i {
if(a[i] > large)
large = a[i];
else if (a[i] < small)
small = a[i];
}
printf (“\n Largest element in vector is %8.2f\n”, large);
printf(“\n Smallest element in vector is %8.2f\n”, small);
}

Run:
Size of vector ? 7
Vector elements ?
3.400 -9.00 12.00 10.00 -6.00 0.00 36.00
Largest element in vector is 36.00
Smallest element in vector is -9.00

Example
/* sort.c: sorting the vector elements in ascending order */
#include
main ()
{
int i,j,k,n;
float a[50], temp;
printf (“Size of vector ?”);
scanf(“%d”, &n);
printf (“\n Vecntor elements ?\n”);
for (i=0; i scanf(“%f”, &a[i]);
/* sorting vector A using selection sort */
for (i=0; I for(j=i+l;j {
/* To sort in descending order change the ‘>’ */
/* operator to ‘<’ in the IF structure */
if (a[I] < a[j])
{
temp = a[i];
a [i] = a[j]
a[j] = temp;
}
}
printf (“\n Vector elements in ascending order: \n”);
for (i=0; i printf (“%8.2f’,a(i]);
}
Run:
Size of vector ? 8
Vector elements ?
91.00 20.00 1.00 7.00 34.00 11.00 -2.00 6.00
Vector elements in ascending order:
-2.00 1.00 6.00 7.00 11.00 20.00 34.00 91.00

Example

/* insert.c: inserting an element into an vector */
#include
main()
{
Int i,j,k,n,pos;
float a[50], item;
printf (“size of vector ?”);
scanf(“%d”,&n);
printf(\n vector elements ? \n”);
for (i=0; i scanf (%f”, &a[i];
printf (“\n element to be inserted ?”);
scanf (“%f”, &item);
printf (“\n position of insertion ? “);
scanf (“%d”, &pos);
/ * Pushing down elements */
n++;
for (k=n; k>=pos; k--_
a[k] = a[k-1];
a[--pos] = item; /* item inserted */
printf (“\n Vector after insertion : \n”);
for (i=0; i printf (“%6.2f”, a[i]);
printf (“\n”);
}

Run:
Size of vector? 6
Vector elements ?
1.00 2.00 3.00 4.00 5.00 6.00
Element to be inserted ? 10.00
Position of insertion ? 1
Vector after insertion :
10.00 1.00 2.00 3.00 4.00 5.00 6.00

Run 2:
Size of vector? 5
Vector elements ?
1.00 2.00 4.00 5.00 6.00
Element to be inserted ? 3.00
Position of insertion ? 3
Vector after insertion :
1.00 2.00 3.00 4.00 5.00 6.00

7.3 MULTIDIMENSIONAL ARRAYS
Often, there is a need to store and manipulate two-dimensional data structures such as matrices and tables. Here, the array has two subscripts. One subscript denotes the row, and the other, the column. As before, all subscripts (row and column) start with 0.

(i) Declaration
The declaration of a two-dimensional array is as follows:
float m[10][20];
Here, m is declared as a matrix having 10 rows (numbered 0 through 9) and 20 columns (numbered 0 through 19). The first element in the matrix (the element at the first row and first column) is:
m[0] [0]
and that at the last row and last column is:
m[9] [19]

(ii) Elements of multidimensional arrays
A two dimensional array marks [4] [3] is shown Figure 7.4. The first element is given by marks [0] [0] which contains 35.5, the second element is marks [0] [1] and contains 40.5 and so on. Figure 7.5 is a pictorial representation of the two dimensional array marks as stored in the memory.


Fig 7.4 Two dimensional matrix: marks [4] [3]




Fig 7.5 Two dimensional array to store marks

Note: The declaration of a two dimensional array, for example, m[10] [20] may be confusing to those who are familiar with other languages such as FORTRAN, where the array subscripts are separated by a comma. Consider the following program typed by a confused programmer.



# include
void main( )
{
int m[10] [20];
m[5] [16] = 13;
printf (“%d\n”, m[5,16]);
}

The first two lines in main() are fine, but the third line wrongly uses a comma inside the square braces, instead of enclosing the two subscripts separately. The danger lies in the fact that comma is an operator in C. Recall that the comma operator causes the expressions to be evaluated from left to right, and the value of the right most expression becomes the value of the entire expression containing the comma operators. In this case, the result of the expression with 5,16 inside the square braces, evaluates to 16 and hence, the printf statement shown above is equivalent to:
printf(“%d\n”, m[16]);

But since the array m is two dimensional, one would feel that m[16] would give a compile time error. But this is not so, since m[16] actually refers to the memory location of the first element in the 17th row. Even though there is no 17th row, C does not check this fact. So there will be no compile time errors on this account. At run time, instead of 13, some other number may get printed, or the program may crash. Needless to say, such errors made in a large program are difficult to detect.

(iii) Accessing two dimensional array elements
The elements of a two dimensional array can be accessed by the following expression:
marks [i][j]
where i refers to the row number and j, the column number.

(iv) Initializing two dimensional arrays
Initialization of a two-dimensional array during declaration is done by specifying the elements in row major order (i.e., with the elements of the first row in a sequence, followed by those of the second, and so on). An example is given below:

int two_dim_int[3] [4] =
{
{1, 2, 3, 4},
{2, 3, 4, 5},
{5, 6, 7, 8}
};

The variable two_dim_int is declared as a two dimensional integer array with certain initial values. The first subscript can be omitted. For example, the declaration below wherein the number of rows(3) is not explicitly specified, is equivalent to the previous one.
int two_dim_int[ ] [4] =
{
{1, 2, 3, 4},
{2, 3, 4, 5},
{5, 6, 7, 8}
};

Also, the inner braces can be omitted, giving the numbers in one continuous sequence. For example, has the same effect as the previous example, but is not as readable as before.

(v) Passing arrays to functions
Arrays can be passed as arguments to functions. Consider the following example:

/* arrfunc.c: passing arrays to functions */
#include
const int Rollno =4;
const int Subject = 3;

/* function declaration */
void display (float marks [Rollno] [Subjects]);

main()
{
float marks [Rollno] [Subjects] =

/* array initialization */
{
{35.5, 40.5, 45.5},
{50.5, 55.5, 60.5},
{65.0, 70.0, 75.5}
{80.0, 85.0, 90.0}
};
/* function call with array as an argument */
display (marks);
} /* end main */
/* function definition to display elements */
void display (float Studentmarks [Rollno] [Subjects])
{
int r,s;
for (r=0; r {
printf (“\n Rollno %d”);
for (s=0; s printf (“%10.24”, Studentmarks [r] [s]);
} /* end for */
} /* end display */

The function declaration in the above program,
void display (float marks [Rollno] [Subjects]);
can also be written as,

void display (float marks [ ] [Subjects]);

The function display visualizes marks as an array, where the number of columns is Subjects. While calling the function, the name of the array is sufficient as an argument. Hence, the function call in main is of the form:
display (marks); /* function call */

The name marks represents the memory address of the array and is similar to using a reference argument. Elements of an array are not copied but the function works with a different name, on the original array itself. Hence, any modifications done to the array in the function are reflected in the array of the caller too. Passing by reference is efficient, as arrays can be very large and copying the entire array into a function consumes time and memory.

The function definition.
void display (float StudentMarks [Rollno] [Subject])
uses the name of the array, datatype and their sizes. Inside the function the elements of the array are accessed by:
studentmarks [r][s]

Example

/* addmat.c: program to add tow matrices */
#include
main()
{
int a[10] [10], vb[10] [10], c[10] [10], i,j,m,n,p,q;
printf (“Input row and column of A matrix \n”);
scanf(“%d %d”, &n, &m);
printf (“Input row and column of B matrix \n”);
scanf(“%d %d”, &p, &q);
/* checks if matrices can be added */
if(n==p)&&(m==q))
{
printf(“matrices can be added\n”);
printf(“Input A-matrix\n”);
for(i=0; i for(j=0; j scanf(“%d”, &a[i][j]);
pritnf (“Input B-matrix \n”);
for(i=0; i for(j=0; j /* Addition of two matrices */
for(i=0; i for(j=0; j c[i][j] = a[i][j] + b[i][j];
printf (“sum of A and B matrices :\n”);
for (i=0, i {
for (j=-; j printf (“%5d”,c[i][j]);
printf(“\n”);
}
} /* endif */
else
printf (“matrices cannot be added \n”);
} /* main */

Run 1:
Input row and column of A matrix
3 3
Input row and column of B matrix
1 2
Matrices cannot be added

Run 2:
Input row and column of A matrix
3 3
Input row and column of B matrix
3 3
Matrices can be added

Input A-matrix
1 2 3
4 5 6
7 8 9

Input B-matrix
1 2 3
4 5 6
7 8 9

Input A and B-matrix
2 4 6
8 10 12
14 16 18

Example
/* trace.c: Trace of the matrix */
#include
main()
{
int a[10] [10], i,j, n, trace;
printf (“Enter the order of A matrix \n”);
scanf (“%d”, &n);
printf (“Input A-matrix\n”);
for (i=0; i for (j=0; j scanf (“%d”, &a[i[ [j]);
/* Trace = Sum of the diagonal elements of the matrix */
trace = 0;
for (i=0; i trace += a[i] [i];
printf (“trace = %d \n”, trace);
} /* main */

Run:
Enter the order of A matrix
3
Input A-matrix
1 2 3
4 5 6
7 8 9
Trace = 15

Example

/* mult.c: program to multiply tow matrixes */
#include
main()
{
int a [10] [10], b [10] [10], c[10] [10], i,j, m,n,ip,k,p,q;
printf (“Input row and column of A matrix :”);
scanf (“%d %d”, &m,&n);
printf (“Input row and column of B matrix:”);
scanf (“% %d, &k, &q);
if (n==k)
{
printf (“matrices can be multiplied \n”);
printf (“resultant matrix is %d X %d\n”,m,q);
printf (“input A-matx \n”);
read_mat (a,m,n);
printf(“Input B-matrix \n”);
/* function call to read the matrix */
read_mat(b,k,q);
/* Multiplication of two matrices */
for (i=0; i for )j=0; j {
c[i] [j] = 0;
for(ip=0; ip c[i] [j] = c[i] [j] + a[i] [ip] * b[ip] [j];
}
printf (“Resultant of A and B matrices :\n”);
write_mat (c,m,q);
} /* end if */
else
{
printf (“Col of matrix A must be equal to row of matrix B \n”);
printf (“matrices cannot be multiplied \n”);
} /* end else */
} /* End of main */
/* function re ad matrix */
read_mat(a,m,n)
int a[10] [10], m,n;
{
int i,j;
for (i=0; i for (j=0; j scanf (“%d”, &a[i] [j]);
}
/* function tow rite the matrix */
write_mat (a,m,n)
int a [10] [10], m,n;
{
int i,j;
for (i=0; i {
for (j=0; j printf (“%5d”, a[i] [j]);
printf (“\n”);
}
}

Run 1:
Input row and column of A matrix: 3 3
Input row and column of B matrix: 3 3
Matrices can be multiplied
Resultant matrix ix 3 X3
Input A-matrix
1 2 3
4 5 6
7 8 9

Input B-matrix
1 2 3
4 5 6
7 8 9
Resultant of A B matrices :
30 36 42
66 81 96
102 126 150
Run 2:
Input row and column of A matrix: 1 2
Input row and column of B matrix: 3 4
Col of matrix A must be equal to row of matrix B
Matrices cannot be multiplied
Example
/* trans.c: Transpose of a matrix */
#include
main()
{
int a [10] [10], b[10] [10], i,j,m,n;
printf (“Input row and column of A matrix:”);
scanf (“%d %d”, &n, &m);
printf (“\n Inpute A-matrix \n”);
for (i=0; i for (j=0; j scanf (“%d”, &a[i] [j]);
/* the rows and columns are interchanged: transpose */
for (i=0; i for (j=0; j b[i] [j] = a[j] [i];
printf (“\n Transpose of matrix A is :\n”);
for (i=0; i {
for (j=0; j printf (“%6d”, b[i] [j]);
printf (“\n”);
}
} /* main */

Run:
Input row and column of A matrix : 3 4
Input A-matrix
1 2 3 4
5 6 7 8
9 6 7 8

Transpose of matrix A is :
1 5 9
2 6 6
3 7 7
4 8 9

STRINGS
Strings are arrays of characters, i.e., they are characters arranged on e after another in memory. To mark the end of the string. C uses the null character. Strings in C are enclosed within double quotes. So, for example,
“My age is 2 (two)”
is a string. The string is stored in memory as ASCII codes of the characters that make up the string appended with 0 (ASCII value of null). ASCII values of all characters are given in Chapter 14, with the help of which we will examine the memory occupied by the string.

Normally, each character is stored in one byte, and successive characters of the string are stored in successive bytes.

Character: M Y a g e i s 2
ASCII Code: 77 121 32 97 103 101 32 105 115 32 50 32

( t w 0 ) \0
40 116 119 111 41 0

The last character, as you can see, is the null character, having the ASCII value zero.

(i) Initializing strings
Following the discussion on character arrays (i.e., a string), the initialization of a string must have the following form, (this is similar to initializing a one dimensional array):

Char month 1[] = (‘J’, ‘a’, ‘n’, ‘u’, ‘a’, ‘r’, ‘y’, 0);
Then the string month is initialized to January. This is perfectly valid, but C offers a special way to initialize strings. The above string can be initialized as:

Char month1 [] = “January”;

The characters of the string are enclosed within a pair of double quotes. The compiles takes care of storing the ASCII codes of the characters of the string in memory and also stores the null terminator in the end. A simple program to display a string is listed below.

/* string.c: string variable */
#include
main
{
char month [15];
printf (“Enter the string”);
gets (month);
printf (“the string entered is %s”, month);
}

In this example, a string is stored in the character string variable month. The string is displayed by the statement:
printf (“The string entered is %s”, = month)

It is a one dimensional array. Each character occupies a byte. A null character (‘\0’) that has the ASCII value 0 terminates the string. Figure 7.6 shows the storage of the string January in the memory. Recall that \0 specifies a single character whose ASCII value is zero.

Fig. 7.6 String stored in a string vairable month
Example:
/* string2.c: illustration using a string literal */
#include
main ()
{
char strc [] = “This is a string literal”;
printf (“%s”, strc);
}
Run:
This is a string literal

7.5 ARRAYS OF STRINGS
An array of strings is a two dimensional array. Consider an example that initializes 5 names in an array of strings and prints them.

/* starray.c: array of strings */
#include
const int NUM = 5;
const int LENGTH = 9;
main ()
{
int j;
char Name [NUM] [LENGTH] =
(“Tejaswi”, “Prasad”, “Prasanth”, “Prakash”, “Anand”};
for (j=0; j printf (“%s\n”, Name [j]);
}
run:
Tejaswi
Prasad
Prasanth
Prakash
Anand



Fig. 7.7 Array of strings

A string is an array; and Name is an array of strings. It can be represented by a two dimensional array of size [5] [9] as shown in Figure 7.7. The second dimension LENGTH specifies the length of the longest array string (9 characters for Prasanth including the terminal character ‘\0’) and each name is accessed by Names[j]. Here, we do not need the second index. Name [j] is sufficient to access string number j in array.

7.6 FUNCTIONS IN string.h

This section describes the functions that help in manipulating strings. To use these functions, the header file string.h must be included in the program with the statement:
#include
strcat
This function concatenates two strings, i.e., it appends one string at the end of another. The function accepts two strings as parameters and stores the contents of the second string at the end of the first. An example is given below.

/* stract.c: Example program for stract */
#include
#include
void main()
{

/* Declare two strings */
char oneString [10] = “Fish”;
char twoString [] = “face”;
/* Put twoString at the end of onestring. */
strcat (oneString, twoString);
printf (oneString);
}

The output of this program is:

Fish face

The central part of the program is the statement,
Strcat (oneString, twoString);
Which places the characters of twostring at the end ofoneString.

Observe that the declaration of oneString has the subscript 10 specifying the size of the string, while the declaration of twoString does not have any size specified. Recall that in the declaration of arrays, if the subscript is omitted, it is assumed to be size of the data with which the array is initialized. So, while the size of the string oneString is 10 (which means that oneString can hold a maximum of 10 characters), the size of twoString is equal to the size of the string face. This string has 4 characters plus a null character, which makes a total of 5. So, the size of the string twoString is 5.

If we declare oneString with the statement,
Char oneString [] = “Fish”;
then oneString will be able to hold a maximum of 6 characters only. When the statement,
strcat (oneString, twoString);
appends the characters of twoString at the end of oneString, the size of oneString would not suffice. This leads to unpredictable results at run time. Hence, in the above program, onestring is declared by the statement,

char oneString[10] = “fish”;
which is safe, since after concatenation, oneString becomes Fish face, which is 10 characters in length, including the null terminator. In general, whenever you use the stract function, check to see whether the first string is large enough to hold the resultant concatenated string. Note, there is no ‘+’ operator in C that can be applied to strings in order to concatenate them. The function strcat described here exists for that purpose.

Strcomp
The function strcmp compares two strings. This function is useful while writing programs for constructing and searching strings as arranged in a dictionary. The function accepts two strings as parameters and returns an integer, whose value is:
* Less than 0 if the first string is less than the second
* Equal to 0 if both are identical
* Greater than 0 if the first string is greater than the second

The function strcmp compares the two strings, character by character, to decide the greater one. Whenever two characters in the string differ, the string which has the character with a higher ASCII value is greater. For example, consider the strings hello and Hello!!. The first character itself differs. The ASCII code for h is 104, while that for H is 72. Since the ASCII code of h is greater, the string hello is greater than the string Hello!!. Once a differing character is found, there is no need to compare the other characters of the strings. The following code fragment compares two strings and output the result.

char str[30], str2[30];
int cmpResult;
scanf(“%s %s”, str1, str2);
cmpResult = strcmp (str1, str2);
if (cmpResult<0 br=""> printf (“str1 else if (cmpResult == 0)
printf (“str1 ==2”);
else
printf (“str1 > str2”);

A sample run is shown below:

azcd abzzi
str1 > str2

Again, note that the operators <, > and == cannot be used directly with strings. To compare strings, use strcmp.

Strcpy
The strcpy function copies one string to another. The function accepts two strings as parameters and copies the second string character by character into the first one, upto and including the null character of the second string. As in the function strcat, you need to be careful to make sure that the size of the string is greater or equal to the second.

For example the following code:
char str1[] = “Will be overwritten”;
char str2[] = “Will overwrite”;
printf (“Before strcpy str1 is \n”);
printf (“%s \n”, str1);
strcpy(“str1, str2);
printf (“After strcpy str1 is \n”);
printf (“%s\n”, str1);

will output:
before strcpy stril is
Will be overwritten
After strcpy strl is
Will overwrite

The operator = cannot be used to assign one string to another. Use strcpy for this purpose.
strlen
This function returns an integer which denotes the length of the string passed. The length of a string is the number of characters present in it, excluding the terminating null character. For example,

char str[] = “Hello”;
printf (“%d\n”, strlen (str));
will output 5, since there are 5 characters in the string Hello.
More on string library functions is given in the chapter on pointers.

7.7 PROGRAMMIN EXAMPLES

Example

/* dup.c: Deleting duplicates in a Vector */
#include
main()
{
int i,j,k,n,num,flag = 0;
float a[50];
printf (“Size of vector ? “);
scanf (“%d”, &n);
num = n;
printf (“\n Vector elements ? \n”)
for (i=0; i scanf (“%f”, &a[i]);
/* removing duplicates */
for (i=0; i for (j=I+1; j {
if (a[i] == a[j])
{
n=n – 1;
for (k=j; k a[k] = a[k+1];
flag = 1;
j=j-1;
}
}
/* use of IF and ELSE statement */
if (flag == 0)
printf (“\n No duplicates found in vector \n”);
else
{
printf (“\n Vector has %d duplicates”, num –n);
printf (“Vector after deleting duplicates : \n”);
for (i=0; i printf (“% 6.2f”, a[i]);
printf (“\n”);
}
}

Run:
Size of vector 7 6
Vector elements ?
1.00 2.00 1.00 3.00 2.00 4.00
Vector has 2 duplicates
Vector after deleting duplicates:
1.00 2.00 3.00 4.00

Example
/* grade.c: Calculating grades of ‘N’ students from 3 tests */
#include
main()
{
int i,j,k,n,m;
float a[50] [10], sum, avg;
char grade [50];
printf (“Number of students ?”);
scanf (“%d”, &n);
for (i=0; i {
sum = 0.0;
printf (“\n Enter 3 scores of student-%d \n”, i+1);
for (j=0; j<3 br="" i=""> {
scanf (“%f”, &a[i][j]);
sum += a[i] [j];
}
avg = sum / 3.0;
a [i] [3] = avg;
if (avg <30 .0="" br="" else="" if..="" of="" use=""> grade [i] = ‘E’;
else if (avg <45 .0="" br=""> grade [i] = ‘D’;
else if (avg <60 .0="" br=""> grade [i] = ‘C’;
else if (avg <75 .0="" br=""> grade [i] = ‘B’;
else
grade [i] = ‘A’;
}

printf (“\n Sl.no. Scores Average Grade \n”);
printf (“\n--------------------------------------\n\n”);
for (i=0; i {
printf (“%d.”, i+1);
for (j=0; j<4 br="" j=""> printf (“%82f”, a[i] [j]);
printf (“%6c”, grade [i]);
printf (“\n”);
printf (“\n--------------------------------------\n\n”);
}
}

Run:
Number of students ? 5
Enter 3 scores of student –1
67.00 86.00 58.00
Enter 3 scores of student –2
20.00 30.00 23.90
Enter 3 scores of student –3
80.00 97.00 73.00
Enter 3 scores of student –4
56.80 47.90 62.00
Enter 3 scores of student –5
45.00 35.00 40.00

Sl.No. SCORES AVERAGE GRADE
------------------------------------------------------------------------------------------------
1. 67.00 86.00 58.00 70.33 B
2. 20.00 30.00 23.00 24.63 E
3. 80.00 97.00 73.00 83.33 A
4. 56.80 47.90 62.00 55.57 C
5. 45.00 35.00 58.00 70.33 B
------------------------------------------------------------------------------------------------

Example

/* var.c: Calculating Mean, Variance and standard deviation */
#include
#include
main()
{
int i,n;
float x[50], mean, variance, sdn;
float sumsq = 0.0, sum = 0.0;
printf (“Calculating standard deviation of a\n”);
printf (“\n Enter size of the list:”);
scanf (“%d”, &n);
printf (“\n Enter the %d items \n”, n);
for (i=0; i {
scanf (“%f”, &x[i]);
sum += x[i]);
}
mean = sum/(float) n;
/* Computing variance */
for (i=0; i sumsq = sumsq + (mean – x[i])* (mean – x[i]);
variance = sumsq/(float)n;
sdn = sqrt (variance); /* Standard deviation */
printf (“\n\n Mean of %5d items : %10.6f\n”,n,mean);
printf (“\n variance : %10.6f\n”,varaince);
printf (“\n Standard Deviation : % 10.6f\n”,sdn);
}
Run:
Calculating standard deviation of a
Enter size of the list : 7
Enter the 7 items
32.00 11.00 90.00 34.00 52.00 24.00 7.00
Mean of 7 items : 35.714287
Variance : 685.918396
Standard Deviation : 26.190044

Example

/* norm.c: Program to compute the norm of the matrix */
#include
#include
main()
{
int i,j,m,n;
float norm, a[10] [10];
float nrm (float [] [], int, int);
printf (“Input row and column of A matrix:”);
scanf (“%d %d”, &n, &m);
printf (“%d %d n”, n,m);
printf (“Input A-matrix \n”);
for (i=0; i for (j=0; j scanf (“%f”, &a[i] [j]);
norm = nrm (a,n,m);
printf (“Norm = %6.2f \n”, norm);
} /* End of main */
/* norm of a matrix = sqsuareroot of the sum of the */
/* squares of the elements of the matrix */
float nrm
(float a[] [], int n, int m)
{
int i,j;
float sum = 0.0;
for (i=0; i for (j=0; j sum = sum + a[i] [j] * a[i] [j];
printf (“Sum = %6.24\n”, sum);
return (sqrt ((double)sum));
}
Run:
Input row and column of A matrix : 3 3
Input A-marix

1.00 2.00 3.00
4.00 5.00 6.00
7.00 8.00 9.00

Sum = 285.00
Norm – 16.88

Example

/* saddle.c: Program to find saddle point in a matrix */
#include
main()
{
int a[5] [5], i,j,min,max,n,m,flag=1,p,q;
printf (“Input the size of matrix:”);
scanf (“%d %d”, &n, &m);
printf (“Enter the elements of the matrix \n”);
for (i=0; i for (j=0; j scanf (“%d”, &a[i] [j]);
/* Find minimum element in row */
for (i=0; i {
min = a[i] [0];
p=i;
q = 0;
/* To check whether ‘min’ is the maximum in column */
for (j=0; j {
if (min>a[i] [j])
{
min=a[i] [j];
p = i;
q = j;
}
}
for (j=0; j{
if(j ! = q)
{
if (a[j] [q] > a[p] [q])
flag = 0;
}
}
if (flag)
printf (“Saddle point a [%d] [%d] = %d\n”, p+1, q+1, a[p] [q]);
else
printf (“No saddle point in row %d\n”, i+1);
flag = 1;
}
}

Run:
Input the size of matrix : 3 3
Enter the elements of the matrix

7 5 5
10 5 8
6 3 3
Saddle point a[1] [2] = 5
Saddle point a [2] [2] = 5
No saddle point in row 3

Example

/* sym.c: Program to find the symmetry of the matrix */
#include
main()
{
int a[10] [10], b[10] [10],i,j,n, flag;
printf (“Input order of the A matrix);
scanf (“%d”, &n);
printf (“Input A-matrix\n”);
for (i=0; i for (j=0; j scanf (“%d”, &a[i] [j]);
/* Transpose of the given Matrix */
for (i=0; i for (j=0; j b[i][j] = a[j] [i];
printf (“Transpose of A matrix : \n”);
for (i=0; i {
for (j=0; j printf (“%5d”, b[i] [j]);
printf (“\n”);
}
/* Find symmetry of a matrix */
for (i=0; i if (a[i] [j] != b[i] [j])
flag = 1;
}
if (flag)
printf (“Matrix is not symmetric \n”);
else
printf (“Matrix is symmetric \n”);
} /* main */

Run 1:
Input order of A matrix : 2 2
Input A-matirx
1 2
3 4
Transpose of A matrix:
1 2
3 4
Matrix is not symmetric

Run 2:
Input order of A matrix : 3 3
Input A – Matrix
1 2 5
2 3 4
5 4 9
Transpose of A – Matrix
1 2 5
2 3 4
5 4 9
Matrix is symmetric


{
min = a[i] [0];
p=i;
q = 0;
/* To check whether ‘min’ is the maximum in column */
for (j=0; j {
if (min>a[i] [j])
{
min=a[i] [j];
p = i;
q = j;
}
}
for (j=0; j{
if(j ! = q)
{
if (a[j] [q] > a[p] [q])
flag = 0;
}
}
if (flag)
printf (“Saddle point a [%d] [%d] = %d\n”, p+1, q+1, a[p] [q]);
else
printf (“No saddle point in row %d\n”, i+1);
flag = 1;
}
}

Run:
Input the size of matrix : 3 3
Enter the elements of the matrix

7 5 5
10 5 8
6 3 3
Saddle point a[1] [2] = 5
Saddle point a [2] [2] = 5
No saddle point in row 3


Tutorial
1. What is an array?
2. How is the integer array a, containing 100 elements, declared in C?
3. What is the subscript of the first element of an array in C?
4. What are the rules for naming arrays?
5. How would you declare an array x containing 50 integer elements followed immediately by 50 real elements?
6. What is the purpose of initializing an array?
7. Is it possible to declare and initialize an array in C simultaneously? If, so, how?
8. If array1 and array2 are dimensioned as follows:
Char array1 [10], array2[10];
and array1 has been initialized, what is the effect of the following?
array2 = array1;
9. What purpose is served by the break statement?
10. What criticism can be leveled against the break statement?
11. Explain the operation of the following expression (assume y has the value 5):
x = (y *=2) + (z=a=4);
12. How is a string stored in an array in C?
13. What declaration would be used for the array bingo, into which the string “I love C” is to be stored?
14. What conversion specification usually is used to read in a string?
15. When the conversion specification %s is used in a scanf statement to read in a string, what is unusual about the way the name of the array is specified?
16. How can one ensure that a scanf statement used to read in a string does not read in more characters than the corresponding character array can hold?
17. Is it obligatory to use all the elements of an array?
18. When a one-dimensional array is being declared, under what condition may the dimension be omitted, with the array name followed by an empty pair of square brackets?
19. What happens if an array is being initialized within its declaration, and too few initialization values are specified within the curly braces?
20. What happens if the number of initializing values is greater than the dimension specified for the array?
21. Must the elements of an array be read in or printed out in order or subscript?
22. When sorting the elements of an array, is it necessary to use another array to store the sorted elements?
23. Where is it legal to declare a new variable?
24. What is the name of the construct used in the following statement, ad how does it operator?
A = (b>c) ? b : c;
25. What is the maximum number of dimensions an array in C may have?
26. True or false: If all the elements of a two-dimensional array are initialized in the declaration of the array, both subscriptions may be omitted.

ANSWERS TO C TUTORIAL

1. An array is an ordered collection of elements that share the same name.
2. int a[100]
3. 0 (zero)
4. The same as for naming regular variables or functions. An array cannot have the same name as a variable or function within the same program.
5. It can’t be done. (All elements of a single array must be of the same type).
6. Before any element of an array can be used, it must have a value. Initializing an array gives a value to each of its elements.
7. Yes. The array declaration is followed immediately by an equal sign. This is followed by the list of values to be assigned (separated by commas) enclosed in braces.
8. A syntax error is fledged by the compiler. One array cannot be assigned to another using the assignment operator. Each element must be assigned individually.
9. It provides a means of immediately terminating the execution of a loop.
10. It violates the tenets of structured programming, in that it permits a jump to another part of the program.
11. The first set of parentheses is evaluated first, multiplying the value of y by 2; the new value of y, 10, is returned by the sub-expression. The second set of parentheses is then evaluated, assigning 4 to a and z and returning that value. The values returned by the two sub-expressions (10 and 4) then are added together to produce the result of 14, which is assigned to x.
12. It is terminated by the null character, which has the ASCII value 0 and is written in C as ‘\0’.
13. Char bingo [9]; /* One element is reserved for the null
Character, ‘\0’ */
14. %s
15. The ampersand (&) is not used, and the array is not subscripted.
16. A maximum field width specifier should be used with the 1%s conversion specification; for example, %10s.
17. No, but the program must keep track of how many elements are are being used, and which ones.
18. If the entire array is being initialized within the declaration.
19. This is perfectly acceptable, as long as the dimension is specified explicitly in the declaration. The initialization values that are specified are assigned to consecutive elements of the array, starting with element 0. The remaining elements are initialized to zero.
20. A syntax error occurs during compilation of the program, and the compilation is aborted.
21. No. the elements of an array (even a character array) may be accessed in any order at all.
22. Not always. In this chapter, the method employed did not use another array. The advantage to using another array is that the original array is retained. Its advantage is that it uses extra memory.
23. At the beginning of the body of a function, and at the beginning of a compound statement.
24. The statement makes use of the conditional expression. If b is greater than c, the conditional expression returns the value of b (the value following the ?); otherwise, it returns the value of c (the value following the :). The returned value is assigned to a. The overall effect is that the larger of the two variables b and c is assigned to a.
25. Theoretically, there is no limit. The only practical limits are memory size and the restrictions imposed by the compiler being used.
26. False. Only the first (row) subscript can be omitted, with the first pair of square brackets left empty. The second subscript must always be explicitly specified.

Keywords
break char do double else float
for if int long return short
unsigned

Exercises
1. What are the arrays? In C, can you have arrays of any data type?
2. In C, what is the index of the first element in an array?
3. What does the name of the array signify?
4. Can array indexes be negative?
5. Illustrate the initialization of a one dimensional array with an example.
6. Illustrate the initialization of a two dimensional array with an example.
7. Show the storage of a two dimensional array in memory with the help of a diagram.
8. Write a program to determine whether a matrix singular or not (solution 4).
9. Write a program to find the inverse of a square matrix (solution 5).
10. Write a program to test for the orthogonality of a square matrix (solution 6).
11. Write a program to maintain a circular queue in an array (solution 7).
12. Implement the following sorting techniques:
(i) bubble sort (solution 8)
(ii) selection sort (solution 9)
(iii) merge sort (solution 10)
(iv) quick sort (solution 11)
(v) heap sort (solution 12)
13. Write a program to find the minimum cost spanning tree by using:
(i) Prim’s algorithm (solution 13)
(ii) Krushkal’s algorithm (solution 14).
14. Solve the 8 queens problem using backtracking (solution 15).
15. Write a program to perform polynomial addition (solution 29).
16. What is the null character and what is it used for, in the context of strings?
17. Point out the difference between:
(i) strcat and strncat
(ii) strcmp and strncmp
18. Write the name of the function in string.h which:
(i) performs case insensitive string comparison
(ii) searches for a character inside a string
(iii) searches for a string inside another string.
19. What happens if the total size of the string after strcat becomes greater than the array size of the string used to hold the concatenated string? Does the compiler report an error?
20. Write a program to concatenate two strings (solution 1).
21. Write a program to count the number of vowels, consonants and spaces in a line (solution 2).





EXAMAPERS123.BLOGSPOT.COM