04 November 2012

Part 10 - Arrays

Topics Covered:

Arrays
Counting digits
Comparing characters numerically



Watch Video >>


Downloadable Files

countdigits.c

countletters.c


Exercises

1. The program countdigits.c is presented as an example of using an array to count and classify digits in the input. Using this program as a starting point, construct a similar program countletters.c which counts the letters in the input. Capital and lowercase letters are to be counted separately. To count each type of letter, declare two arrays as follows:

int upper[26] = {0};
int lower[26] = {0};

Note: Specifying all 26 0's in the braces is not necessary. The initializer {0} means to explicitly initialize the element at index 0 to the value 0, and all other elements will be implicitly initialized to zero. However, leaving off the initializer does not initialize any of the elements. So, it is probably best to use an initializer unless you have a specific reason not to.

To test whether each character is a capital letter, use the expression (c >= 'A' && c <= 'Z'). A similar expression may be used to test whether a character is a lowercase letter.

Questions

1. Predict the return code of the following programs. Notice that no input/output is being done, so no header files are needed.

(a)

int main()
{
    unsigned char data[50];
    int sum = 0;
    for (int i=0; i < 50; i++)
        sum += data[i];
    return sum;
}

(b)

int main()
{
    unsigned char data[50] = {5, 4, 3, 2, 1, 0};
    int sum = 0;
    for (int i=0; i < 50; i++)
        sum += data[i];
    return sum;
}

(c)

int main()
{
    unsigned char data[50] = {5};
    int sum = 0;
    for (int i=0; i < 50; i++)
        sum += data[i];
    return sum;
}

Links

An example of array initialization in C - Provides a complete example of the various array initialization options in C.

3 comments:

  1. Please show me where in the C standard it says that 'Z' - 'A' is 26, that these supposed 26 characters consist solely of the set of uppercase letters or that they are in order. Your uppercase checks break when EBCDIC is the character set being used. I suggest using isupper.

    ReplyDelete
    Replies
    1. If anything I would expect 'Z'-'A' is 25. In any case make the following assumptions for the purpose of the exercise:
      1. the input includes only small letters, capital letters or digits
      2. characters of the same class are in the same numerical range
      For real programs that are meant to be used in real life, use isupper() as you mentioned.

      Delete
  2. You are teaching people to write non-portable code. I'm sure your students will become very good at it.

    ReplyDelete