Make your own free website on Tripod.com

Lesson 6: Arrays.

Prev || Home || Next

Bar_line.gif (11170 bytes)

   C provides a facility called array that enables the user to combine similar data types into a single entity. An array is a group of related data items that share a commaon name. Ordinarily variables are capable of holding one value at atime. If there is a large amount of similar data to be handeled, then using a different variable for each data item would make job tedius, confusing. Instead, on combining all this similar data into an array, the whole task of otganising and manipulating data would become easier.

    ex. We can define an array named salary to represent a set of salaries of a group of employees.

           int salary[10];          

n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9]

            Here size of array is 10 n[0], n[1], ... , n[9] are the elements of array salary[10]. This is a single dimension array. Here 10 storage places are reserved in the memory where different numbers can be stored. The ability to use a single name to represent a collection of items enables to develop efficient programs. Arrays can be of following types

   1) integer type array

   2) float type array

   3) character type array

   To initialize an integer type array

      int n[5]={5,32,64,15,60};

   To initialize a float array

      float p[5]={1.0,2.0,4.5,6.7,9.0};

   To initialize a character type array

      char name[10]="Raju";

      name[10] is a character type array. Each character of the string is treated as an element of the array name and is stored in the memory as given above. When the compiler seex a character string, it terminates it with an additional null character. Thus the array name[10] can hold maximum 9 characters as it ends with null character.

   Two-Dimensional Arrays:

                                                     We have seen how a list of values can be stored in a single dimension array. But there maybe situations where a table of values will have to be stored. Consider the following data table, ehich shows the value of sales of three items by four salesman.

Salesman Item 1 Item 2 Item 3
Salesman 1 310 275 365
Salesman 2 210 190 325
Salesman 3 405 235 240
Salesman 4 260 300 380

    The table contains a total of 12 values, three in each line. This table can be considered as a matrix with four rows and three columns. C allows us to define such table of items by using two-dimensional arrays as given below.  

                          int v[4][3];

  Column 0 Column 1 Column 2
Row 0 310 [0][0] 275 [0][1] 365 [0][2]
Row 1 210 [1][0] 190 [1][1] 325 [1][2]
Row 2 405 [2][0] 235 [2][1] 240 [2][2]
Row 3 260 [3][0] 300 [3][1] 380 [3][2]

    To initialize a two dimensional array

                        int table[2][3]={{0,0,0},{1,1,1}};

    Program:- To print matrix and print its row wise total using arrays and for loop.

   main()

    {

        int v[4][3],i,j,tot;

        for(i=0;i<=3;i++)

        {

            for(j=0;j<=2;j++)

            {

                printf("Enter the number\n");

                scanf("%d",&v[i][j]);

            }

        }

        for(i=0;i<=3;i++)

        {

            tot=0;

            for(j=0;j<=2;j++)

            {

                printf("%4d",v[i][j]);

                tot=tot+v[i][j];

            }

            printf("%4d",tot);

            printf("\n");

            }

    }

   Handling of Character Strings:

                                                                A string is an array of characters. A string is a group of characters(except double quote sign) defined between double quatation marks. The common operations performed on character strings are reading and writing strings, combining strings together, copying one string to another, comparing strings for equality & extracting a portion of a string.

    Reading Strings from Terminal:

   Reading words:- The familiar input function scanf() can be used with %s format specification to read in a string characters.

                                         ex. char address[15];

                                               scanf("%s",address);  

                               The problem with the scanf function is that it terminates its input on the first white space it finds. Therefore if the word NEW YORK is typed in at the terminal it will read only NEW , since the blank space after the NEW will terminate the string.

    Reading a line of text:- We have seen how scanf() is not useful to read a line of text from terminal as its terminal the as and when a blank space appears. We can use getchar() function to read a single character from the terminal. This function can be used repeatedly to read sucessive single characters from the input and place then into a character array. Thus, an entire line of text can be read and stored into an array. The reading is terminated when enter key is pressed and the null character is then inserted at the end of the string.

    Program: To read a line of text from terminal

    #include<stdio.h>

   main()

   {

        char line[21],character;

        int c=0;

        printf("Enter text.press<Enter>at end\n");

        while(character!='\n')

        {

            character=getchar();

            line[c]=character;

            c++;

        }

        c--;

        line[c]='\0';

        printf("\n%s\n",line);

    }

    C does not provideoperators that work on strings directly. We cannot assign one string to another directly.

            string1="ABC";

            string2=string1;

            These statements are invalid in C.

    Writing Strings to Screen:- We have used the printf() function with %s format print strings to the screen. For ex. printf("%s",name); can be used to display the entire contents of the array name. We can also specify the precision with which the array is displayed ex. %10.4 indicates that first four characters are to be printed in a field width of 10 columns.

    String handling functions:

Function Action
strcat() Concantrates two strings.
strcmp() Compares two strings.
strcpy() Copies one string to another.
strlen() Finds the length of string.

    strcat() Function: The strcat() function joins teo strings together.

                               strcat(str1,str2);

                               Where str1 and str2 are two character arrays. When function strcat is executed, str2 is appended to str1. It does so by removing the null character at the end of str1 and placing str2 there. ex.

                str1=VERY;

                str2=GOOD;

                strcat(str1,str2);  

                    The above code will result in to VERY GOOD. We must make sure that the size of str1 is large enough to accomodate the final string.

 

    strcmp() Function: The strcmp() function compares two strings and returns 0 if they are equal. If they are not equal , it returns the numeric difference between the first non matching character in the string.

        strcmp(str1,str2);

    ex.   strcmp(name1,name2);

            The statement strcmp("RAM","RAM"); will return 0.

            The statement strcmp("their","there"); will return a value of -9 which is the numeric difference between ASCII "i" and ASCII "r".

 

    strcpy(): The strcpy function works almost like a string assignment operator.

                  strcpy(str1,str2);

                    this will assign the content of str2 to str1. Str2 may be a character array variable or a string constanat.

                    strcpy(city,"DELHI");

                    will assign the string "DELHI" to the variable city. Similarly with the statement                                                                                                                          strcpy(ct1,ct2);

 

   strlen() Function: This function counts and returns the number of characters in a string.                                         n=strlen(string);

                            where n is an integer cariable which recieves the value of the length of the string.

Bar_line.gif (11170 bytes)

Prev || Home || Next