week2 Arrays

Document Sample
week2 Arrays Powered By Docstoc
• Why we need data structure?
• Simple data types use a single memory cell to
  store a variable.
• Sometimes (for example scores of a class) it is
  more efficient to group data items together in main
• C allows to group related data items together into
  a single composite data structure.
• Array is one such data structure.
• Array => A collection of data items of the same
     Declaring & Referencing Arrays
  • Array => collection of two or more adjacent memory cells
    (array elements).
  • To set up an array in memory, we must declare
         - the name of the array and
         - the number of cells associated with it.
    int x[5];
                                          Array x

Instructs the compiler              2      4  7    9   1
to associate 5 memory
cells with the name x
                                   x[0] x[1] x[2] x[3] x[4]
       array subscript
Subscripted variable => x[0]
                       Read as x sub zero.
                    Array Subscripts
• Array subscript=> integer enclosed in brackets
                 => its value in the range: 0 - (array_size - 1).
• Use of array subscript => to differentiate between the individual
                            array elements.
                        => to specify which array element is to be
• We can use any expression of type int as an array subscript.
  typedef enum
  { monday, tuesday, wednesday, thursday,friday}
  int score[NUM_CLASS_DAYS];

               Five class days
                      Array subscript
  typedef enum
  { monday, tuesday, wednesday, thursday,friday}
  int score[NUM_CLASS_DAYS];

We can use enumeration constants monday through friday as
array subscripts since the they are represented by the integers
0 through 4.                                             array subscript
                         score [monday]         5        array value
                         score [tuesday]        7
                         score [wednesday]      4
                         score [thursday]       9
                         score [friday]         4
                  Array Initialization
• If there are fewer initializers than elements in the array, the
  remaining elements are automatically initialized to zero.
  Example: int n[10] = {0};
  Note: Arrays are not automatically initialized to zero.
         The programmer must at least initialize the first
  element to zero.
• Initialize an array with declaration:
          int odd_num[5] = {1, 3, 5, 7, 9};
          int odd_num[] = {1, 3, 5, 7, 9};
• Syntax error:
•         int n[5] = {3, 5, 7, 9, 11, 12}

   5 array elements             6 initializers
               Sequential Access
• We can access the elements of an array in sequence by
  using an indexed for loop.
         - Loop control variable runs from zero to one less
           than the array size.
         - Loop counter is used as an array index(subscript)
           to access each element in turn.
  int cube[5], i;
  The for loop
  for (i = 0; i < 5; ++i)
      cube[i] = i * i * i;   initializes this array :
                                    0    1     8    27   64
     Compute the Sum and the Sum of
         the Squares of all Data
sum = x[0] +x[1] + x[2] + x[3] + x[4] + x[5] =    x[i];
sum_sqr = x[0] 2 +x[1] 2+ x[2] 2+ x[3] 2+ x[4] 2+ x[5]2 =    x[i]2;

int i, sum = 0;
int sum_sqr = 0;
for (i = 0; i < MAX_ITEM; ++i)
       sum += x[i];            or sum = sum + x[i];
       sum_sqr += x[i] * x[i]; or sum_sqr = sum_sqr + x[i] * x[i];
Array Elements as Function Arguments
 •   #include <stdio.h>                        Array x
 •   main()
 •   {                                 2     4     7   9   1
 •     int x[5] = {2, 4, 7, 9, 1};
 •     int i;
 •     printf(“The first element is: %d\n”, x[0]);
 •   }
       Result: The first element is: 2

 • Another function: scanf(“%d”, &x[2]);
     The scanned value will be stored in the
     array element x[2].
      Array as Function Arguments
• We can also pass arrays as function arguments.
• A array name with no subscript appears in the argument
  list of the function.
• The address of the initial array element is stored in the
  function‟s corresponding formal parameter.
  Void fill_array ( int list[],      // list of n integers
                      int n,        // number of list elements
                      int in_value) // initial value
      int i;
      for ( i = 0; i < n; ++i)
          list[i] = in_value;
      Array as Function Arguments
• Data Areas Before Return from fill_array(x, 5, 1).

     Calling function             Function fill_array
        Data Area                    Data Area
             x                           list
      [0]    1
      [1]    1                            n
      [2]    1
      [3]    1
      [4]    1

            Array as Function Arguments
• The function manipulates the original array, not its own personal
• So an assignment to one of the array elements by a statement in the
  function changes the contents of the original array.
                 list[i] = in_value;
• ANSI C provides a qualifier const to notify the C compiler that
   - the array is only an input to the function and
   - the function should not be allowed to modify array elements.
   - the elements of the array become constant in the function body.
   - any attempt to modify an element of the array in the function
       body results in a compile time error.
• Example:
  int get_max(const int list[], // input- list of n integers
               int        n)    // input- number of list elements
              Returning an Array Result
• In C, it is not legal for a function‟s return type to be an array.
• It requires the use of an output parameter to send the result array
  back to the calling function.
  void add_arrays(const int arg1[],           // input
                    const int arg2[],        // input
                    int        argsum[], // output
                    int        n)           // input
  for (i = 0; i < n; ++i)
       argsum[i] = arg1[i] + arg2[i]; // adds corresponding elements
                                        // of arg1 and arg2
       Why we apply Static to a Local
           Array Declaration?

• We can apply static to a local array declaration so that
     - the array is not created and initialized each time
        the function is called, and
     - the array is not destroyed each time the function is
       exited in the program.
     - this reduces program execution time particularly
        for programs with frequently called functions that
        contain large arrays.
• A stack is a data structure in which only the top element can be
• A stack of plates in cafeteria.
• A customer always takes the top plate.
• When a plate is removed, the plate beneath it moves to the top.

       Stack of three characters                 Top of the stack

Push => storing an item in a stack
pop => removing an item from a stack
                        Function push
void push(char stack[], // input/output - the stack
           char item,       // input - data being pushed onto the stack
           int *top,       // input/output - pointer to top of stack
           int max_size) // input - maximum size of stack
   if (*top < max_size - 1)
           stack[*top] = item;
                      Function Pop
Char pop(char stack[], // input/output - the stack
           int *top)       // input/output - pointer to top of stack
   char item;       // value popped off the stack
   if (*top >= 0)
            item = stack[*top];
             item = STACK_EMPTY;
    return (item);
  How to create a stack using Array?
int s_top = -1;

The statements :
push(s, „2‟, &s_top, STACK_SIZE);
push(s, „+‟, &s_top, STACK_SIZE);       C
push(s, „C‟, &s_top, STACK_SIZE);       +
     create the stack :

pop(s, &s_top);
     create the stack:
                Searching an Array
• We search an array to determine the location of a
  particular value (target).
• Example: We need to search an array to determine the
  score of a particular student.
• Two popular techniques: linear search and binary search
  Linear search:
• To search an array, first we need to know the array
  element value we are seeking ( target).
• Then we have to examine each array element whether it
  matches the target by using a loop.
• When the target is found, the search loop should be
 Algorithm for Searching (Linear) an Array
1 Assume the target has not been found.
2 Start with the initial array element.
3 Repeat while the target is not found and there are more array
       4 if the current element matches the target
            5 Set a flag to indicate that the target has been found.
           6 Advance to the next array element.
7 if the target was found
        8 Return the target index as the search result.
        9 Return -1 as the search result.
Function for Linear Searching of an Array
 #define NOT_FOUND -1
 int search(const int arr[], int target, int n)
      int i = 0, found = 0, where;
      while (!found && i < n)           // Compare each element to target
                if (arr[i] == target)
                        found = 1;
      if (found)                      // Returns index of element matching target or
                where = i;            // NOT_FOUND
                where = NOT_FOUND;
      return (where);
                       Binary Search
• The binary search algorithm eliminates on ehalf of the elements
  in the array being searched after each comparison.
• The algorithm locates the middle element of the array and
  compares it to the target.
• If they are equal, thetarget is found and the array subscript of that
  element is returned.
• If they are not equal, the problem is reduced to searching one half
  of the array.
• If the target is less than the middle element of the array, the first
  half of the array is searched.
• Otherwise the second half of the array is searched.
• If the target is not found in the specified subarray, the algorithm
  is repeated on one quarter of the original array.
• The search continues until the target is equal to the middle
  element of a subarray, or until the subarray contains one element
  that is not equal to the target.
Function for Binary Searching of an Array
  int binarySearch( int list[], int target, int low, int high )
       int middle;
       while ( low <= high )
                 middle = ( low + high ) / 2;
                if ( target == list[middle] )
                return middle;
                else if ( target < list[middle] )
                high = middle - 1;
                low = middle + 1;
         return -1;
Comparison of Linear and Binary Search
• Linear search compares each element of the array with the target.
  On average , therefore the program will compare the target with
  half of the elements of the array.
• Linear search works well for small arrays or for unsorted arrays.
  However, for large arrays linear searching is inefficient.
• For a large and sorted array, the high speed binary search
  technique can be used.
• In a worst case scenario, searching in an array of 1024 elements
  will take only 10 comparisons using a binary search. A array of
  one billion elements takes a maximum of 30 comparisons to find
  the target.
• 2 10 = 1024 1000
• 2 30 = 1024 * 1024 * 1024 1000000000
                     Sorting an Array
• Many program executes more efficiently if the data are sorted
  before processing.
• Example: You grade reports can be sorted according your student
  ID numbers. A bank sorts all checks by account number.
• Selection sort is a fairly simple but not very efficient.sorting
• To perform a selection sort of an array of n elements, first you
  have to locate the smallest element in the array.
• Then switch the smallest element with the element at subscript 0.
• Then locate the smallest element remaining in the subarray with
  subscripts 1 through n -1.
• Then switch the the smallest (second smallest) element in the
  second position.
• And so on.
        Algorithm for Selection Sort

1 for each value of fill from 0 to n -2
        2 Find index_of_min, the index of the smallest
          element in the unsorted subarray list[fill]
          through list[n -1].
         3 if fill is not the position of the smallest element
              4 Exchange the smallest element with the
                  one at position fill.
              Function select_sort
int get_min_range (int list[], int first, int last);
void select_sort (int list[], int n)
    int fill, temp, index_of_min;
    for (fill = 0; fill < n -1; ++fill)
           index_of_min = get_min_range(list, fill, n -1);
           if (fill != index_of_min)
                     temp = list[index_of_min];
                     list[list_of_min] = list[fill];
                     list[fill] = temp;
                      Selection Sort
• Trace of selection sort
Fill is 0. Find the smallest element
in subarray list[0] through list[3]    74   45   83   16
and swap it with list[0]

Fill is 1. Find the smallest element   16   45   83   74
in subarray list[1] through list[3]
- no exchange needed.

Fill is 2. Find the smallest element   16   45   83   74
in subarray list[2] through list[3]
and swap it with list[2].

                                       16   45   74   83
                   Multidimensional Array
• Multidimensional array => array with two or more dimensions.
• We use two dimensional arrays to represent tables of data,
  matrices, and other two-dimensional objects.
• A two dimensional object is a tic-tac-toe board.
• The array declaration: char tictactoe[3][3]; or char tictactoe[][3];
• The array initialization:
     char tictactoe [3][3] = {{„ „, „ „, „ „}, {„ „, „ „, „ „}, {„ „, „ „, „ „}};

                                           0     1   2
                                0         O     O   X
                            Row 1         X      X       O
                                2         O      X       X
        Array with Several Dimensions
• int enroll [MAXCRS][5][4]               Used to store the enrollment
                                          data for a school.
          course      campus       year
Problem: College offers 100 (MAXCRS) courses at five different
campuses. We numbered the freshman year 0, the sophomore
year 1, and so on. Find the number of juniors in all classes at all
campuses. Students will be counted once for each course in which
they are enrolled.
    int i, j,
        num_junior;             // number of juniors
        num_junior = 0;
    for ( i = 0; i < MAXCRS; ++i)
          for ( j = 0; j < 5; ++j)
                   num_junior += enroll[i][j][2];

• String is a data structure.
• String is a series of characters treated as a single unit.
• A string may include letters, digits, and various special
  characters such as +, -, *, /, $, and others.
• String literal or string constants in C are written in double
  quotation marks as “Daniel Boles”.
• printf or scanf uses a string constant as the first argument.
          printf (“”Sum = %.3f”, sum);
          scanf(“%s”, word);
      Why strings are important ?
• Many computer applications are concerned with
  the manipulation of textual data rather than
  numerical data.
• Computer-based word processing systems enable
  a user to compose letters, term papers, newspaper
  articles, and books.
• Chemist works with elements and compounds
  whose names often combine alphabetic and
  numeric characters (e.g., C12 H22O11).
• Many mathematicians, physicists, and engineers
  use strings of characters and numeric data.
Declaring and initializing String Variables
• C implements the string data structure using either a character
  array or a variable of type char *.
       char color[] = “blue”; // creates a 5-element array color
                                  containing characters „b‟, „l‟, „u‟,
                                  „e‟, and „\0‟.
       char *colorPtr = “blue”; // creates pointer variable colorPtr
                                      that points to the string “blue”
                                      somewhere in memory.
  Both declarations initialize a variable to the string “blue”.

        Color in memory after this declaration and initialization.

                       [0] [1] [2] [3] [4]              Null character
                                                        that marks the
                        b    l    u    e    \0          end of a string.
• A string can be assigned to an array using scanf.
  char word[20];
  scanf(“%s”, word); // The string entered by the user is stored
                          in word.
   word is an array which is a pointer.
   So the & is not needed with argument word.

• Function scanf will read characters until a space, newline, or
  end-of-file indicator is encountered.
• When it comes across a whitespace character, scanning stops,
  and scanf places the null character at the end of the string of the
• When the scanf function is scanning a string, if there is more input
  data (with no blanks) than will fit in the array output argument,
  scanf copies in the whole string overflowing the output argument
  because scanf has no way of knowing the array‟s declared size.
  char dept[7]; // Note that the string should be no longer than 6
                    characters to leave space for the terminating
                    NULL character.
  scanf(“%s”, dept); If the data entered as chemistry:
                                        Space not allocated for dept

        [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
         c h     e m i       s t     r   y \0
• For a character array to be printed as a string , the array must
  contain a terminating NULL character.
                    Arrays of Strings
• A string is an array of characters.
• An array of strings is a two-dimensional array of characters in
   which each row is one string.
                            #define NUM_DAY 7
To declare an array days
to store 7 days, each of
which is less than 20      #define NAME_LEN 20
characters long.
                            char days[NUM_DAY][NAME_LEN];

 char days[7[20] = {“Sunday”, “Monday”, “Tuesday”,“Wednesday”,
                     “Thursday”, “Friday”, “Saturday”};
                 String Assignment
• We do use the assignment symbol in a declaration of a
  string variable with initialization, this context is the only
  one in which the operator means to copy the string (right
  operand) into the variable (left operand).
  char str[20] = “Initial Value”; // valid
  str = “Initial Value”; // invalid
  Array name with no subscript represents the address of
  the initial array element.
  This address cannot be changed through assignment.
  So the last line will cause a compiler error message such
  as Invalid target of assignment:
                  String Assignment
• C provides the string assignment operations through library
• The library string.h provides functions for substring,
  concatenation, string length, string comparison, etc.
• Some selected string library functions:
  strcpy => makes a copy of source, a string, in the character array.
                  Strcpy(s1, “hello”);
  strcat => Appends source to the end of dest.
                  Strcat(s1, “and Physics”);
  strcmp => compares s1 and s2 alphabetically, and returns
             a negative value if s1 precedes s2,
             a zero if the strings are equal,
             a positive value if s2 precedes s1.
• When the strcpy function is copying a string, if there is more input
  data than will fit in the destination variable (dept), strcpy copies in
  the whole string (second argument) overflowing the dept .
• char dept[7]; // Note that the string should be no longer than 6
                     characters to leave space for the terminating
                     NULL character.
  strcpy(dept, “chemistry”); would overflow dept storing the final
  characters „r‟, „y‟, and „\0‟ in memory allocated for other
  The values of these other variables would change spontaneously.
                                        Space not allocated for dept

        [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
         c h     e m i       s t     r   y \0
• Another string-copying function is strncpy.
• It takes source, destination, and the number of characters to be
• It does not add a null character.
• If the string to be copied is shorter than n characters, the remaining
  characters stored are null.Example: strncpy(dept, “Math”);
                                  [0] [1] [2] [3] [4] [5] [6]
                                   M a       t    h \0 \0 \0
• When the source string is longer than n characters, only the first n
  characters are copied. Example: Strncpy(dept, “Chemistry”);
    Prevents overflow.            [0] [1] [2] [3] [4] [5] [6]
    It has not stored a
                                   C   h     e   m     i    s    t
    valid string in dept.
• To prevent overflow of destination string and
• to prevent an invalid string stored in dept
– One can assign as much as will fit of a source string to a
  destination of length dest_len by using the statements:

    strncpy(dest, source, dest_len - 1); // prevents overflow
    dest[dest_len - 1] = „\0‟;          // valid string
• W need to reference a substring of a longer string.
  char last[20], first[20], middle[20], middle[20];
  char pres[20] = “Adam, John Quincy”;

 srtncpy(last, pres, 5);                 Strcpy(middle, &press[12]);
     last[5] = „\0‟;

                 strncpy(first, &press[7], 4);
                        first[4] = „\0‟;
   Longer String: String Concatenation
• Function strcat appends its second argument, a string to its first
  argument, a character array containing a string.
• The first character of the second argument replaces the NULL
  („0‟) that terminates the string in the first argument.
• The programmer must ensure that the array used to store the first
  string is large enough to store the first string, the second string,
  and the terminating NULL character.

  char f1[15] = “John”, f2[15] = “Jacqueline”,
        last [15] = “Kennedy”;
  strcat(f1, last);
  strcat(f2, last) // invalid overflow of f2
      Longer String: String Concatenation
• Two critical questions:
   - Is there enough space in the output parameter for the entire
     string being created?
   - Does the created string end in „\0‟?

  if (strlen(s1) + strlen(s2) < STRSIZ) // function strlen returns the
     {                                    // value of its string argument.
          strcat(s1, s2);                  // it does not count the „\0‟
        strncat(s1, s2, STRSIZ - strlen(s1) - 1);
        s1[STRSIZ - 1] = „\0‟;
Difference between a character & a string
• Difference between the internal representations of the character
  „P‟ and the string “P”.

           P               P    \0   ?      ?    ?    ?   ?   …..

    character „P‟                        string “P”
                   String Comparison
•   Characters are represented by numeric codes.
•   We use relational and equality operator to compare characters.
•   Example:
•   ch1 < ch2 is used to test character variables in decision
•   We cannot use the operator to compare strings because in C,
    strings are represented by arrays.
•   str1 < str2 it is not checking whether str1 precedes str2
•   It determines whether the place in memory where storage of str1
    begins precedes the place in memory where str2 begins.
•   str1 and str2 represent the addresses of the initial elements of
    arrays str1 and str2.
                   String Comparison
• Ch1 < ch2 is true if the numeric character code value of ch1 is less
  than the code in ch2.
• ANSI C extends this concept to strings by stating the following
  two conditions to define “less than”
   – If the first n characters of str1 and str2 match and str1[n],
       str2[n] are the first nonmatching corresponding characters,
       str1 is less than str2 if str1[n] < str2[n].
       str1 step       First 2 letters match.
       str2 stop       str1[2] < str2[2] since „e‟ < „o‟

   – If str1 is shorter than str2 and all the characters of str1 match
     the corresponding characters of str2, str1 is less than str2.
     str1 harm
     str2 harmful
• Strcmp(str1, str2) returns
     - negative integer if str1 is less than str2.
           Example: str1 “carrot”
                       str2 “spinach”
     - zero if str1 equals str2.
           Example: str1 “carrot”
                      str2 “carrot”
     - positive integer if str1 is greater than str2.
           Example: str1 “spinach”
                       str2 “carrot”
• strncmp(str1, str2, n) compares only the first n
  characters of the two strings.
  Example: str1 “strength”
            str2 “string”
  strncmp(str1, str2, 3) returns
      - zero because “str”matches “str”
  strncmp(str1, str2, 4) returns
      - negative integer because “stre” precedes “stri”
           Example of array of pointers
• Multiple ordering of a list of strings can be maintained by storing
  the strings once and creating arrays of pointers for additional
• The original list is a list of names in which applications were
• Names is an array of pointers through which the list can be
  accessed in alphabetical order.
• Each pointer points to the first character of its corresponding
        names[0]                 „J‟ „o‟ „h‟ „n‟ „\0‟
        names[1]                 „C‟ „y‟ „n‟ „t‟ „h‟ „i‟ „a‟ „\0‟
        names[2]                 „D‟ „a‟ „v‟ „i‟ „d‟ „\0‟
        names[3]                 „B‟ „a‟ „r‟ „b‟ „a‟ „r‟ „a‟ „\0‟
           Character Handling Library
• The ctype library provides functions for classification and
  conversion of single characters.
• function isdigit determines whether its argument is a digit (0-9).
• function isalpha determines whether its argument is an uppercase
  letter (A-Z) or a lower case letter (a-z).
• Function islower determines whether its argument is a lowercase
  letter (a-z).
• Function isupper determines whether its argument is an uppercase
  letter (A-Z).
• Function tolower converts an uppercase letter to a lowercase
• Function toupper converts an lowercase letter to an uppercase
    String-to-Number & Number-to-String
• The following conversions are constantly being carried out by the
  library functions scanf and printf
      - The conversion of a string like “3.14159” to the type double
        numeric value it represents
      - The conversion of a number like -36 from its internal
         representation in computer memory to the three-character
         string “-36”.
  Use of scanf: double x;
                  sanf(“%lf”, &x); -8 (data) -8.0 (value stored)
  Use of printf: char str[] = “fantastic”;
                   printf(“%s”, str); fantastic (output)
• sprintf works exactly like printf except that instead of printing the
  result, it stores the result in the character array accessed by its
  initial argument.

  char s[100];
  int month, day, year;
  sprintf (s, “%d %d %d”, month, day, year);

 month          day          year                     s
   8             23          1999              8 / 23/ 1999 \0
• The sscanf function works exactly like scanf except that instead of
  taking the data values for output parameters from the standard
  input devices, it takes data from the string that is its first argument

  char word[100];
  int num;
  double val;
  ssanf(“ 23 36.4 hello”, “%d %lf %s”, &num, &val, word);store
  values from the first string.

                   num          value                  word

                    23          36.4                  hello\0

Shared By: