CSC 161 Grinnell College Spring, 2010
 
Imperative Problem Solving and Data Structures
 

Arrays in C

Goals

This lab provides experience using arrays in the C programming language.

Steps for this Lab

  1. Integers in Base 2
    1. The following program fragment prints the digits of the number 'x' in base two, but in reverse order:

              int x = 22;
              while (x > 0) {
                 printf("%d", x % 2);
                 x = x / 2;
              }
              printf("\n");
      
      For example, if x is 22, which is represented as 10110 in base 2, the program will output "01101". Write a small program that includes this program fragment, and verify that it will print "01101" when x is set to 22.

      Do you understand the algorithm? If not, consider the same algorithm but replace each '2' with '10'. It will print the digits of x (in base 10) in reverse order. Try it if you are not completely sure, and then see if you understand the base 10 algorithm.

    2. Modify your program from the previous exercise so that it uses an an array to store each digit of the base two representation of the number. Then print out the digits in the correct order. Verify that your program will now print "10110" when x is set to 22.

  2. Out-of-bounds Array Indices:
    1. Write a program that prompts for and accepts three numbers from the user, storing them in a 3-element array. Your program should then ask the user for an index number, check whether the given index is valid, and either print out the value stored at the given location or print an error message (if the index is invalid).

    2. Once the program is working correctly, modify it so that it does not verify the correctness of the array index. What happens when you enter inappropriate index values? You may want to try reasonably small errors (say index=3) as well as ridiculous indices (say index=123456789). Do you understand the results that you get?

  3. Passing Arrays to Functions:

    Arrays may be used as parameters to functions, but since arrays in C do not store information about their lengths, you will frequently need to pass the array length as well.

    Note that, although all parameters are passed by value in C, when we pass arrays it is actually the address of the array that is passed. Therefore, a function can modify the values stored in the original array argument. (We will study this more carefully in a few days when we consider pointers in C.)

    1. In mathematical computations, arrays can be used to represent vectors in n-space (e.g., a 3-element array can represent a 3-dimensional vector). The 1-norm of a vector is the sum of the absolute values of the vector components.

      Write a function named oneNorm that computes the 1-norm of a vector having n components. Use the function fabs from the math library to compute absolute values of floating-point numbers. The prototype of your function should be

         double oneNorm( double v[], int n )
      
      where v represents the vector and n represents the number of components (i.e., the dimensionality) of the vector.

      Write a main function that reads in a vector in R5 (use an array of type double), calls your function oneNorm, and prints the vector's 1-norm.

      Don't forget to #include <math.h> and compile with the "-lm" flag, and don't forget to test your program.

    2. The Euclidean norm of a vector v is given by the square-root of the sum of the squares of its components. (So the Euclidean norm is what you may think of as the "length" of a vector. However, all of the vector norms are different definitions of vector length.)

      In the same program that you started in the previous exercise, write a function that computes the Euclidean norm (also known as the 2-norm) of an given vector.

      Of course, being the proud programmer you are, you will test this function thoroughly as well.

    3. One vector can be subtracted from another (of the same dimensionality) by subtracting the corresponding elements. Note that this operation yields a vector.

      The distance between two vectors v and w is defined to be the norm of their difference.

      Write a C function that computes the distance between two given vectors. One parameter to the function should be the type of norm that should be used to compute the distance. You should make use of the functions prepared in parts a and b. The prototype of your function should be as follows:

              double distance( double v[], double w[], int n, int norm )
      

      If norm has a value other than 1 or 2, return the value -1. (Note that this value can not possibly be a valid distance.)

      Modify your main function from above to test this function.

  4. (Optional — as time permits)
    Two-Dimensional Arrays

    In C, we can declare a 2-dimensional integer array named table with

       int table[rows][cols];
    
    where rows and cols hold integer values. Individual elements in the 2d-array are referred to with
        table[i][j]
    
    where i indicates the row number and j indicates the column number in the array. Beware that, like 1-dimensional arrays in C, the array subscripts range from 0 to (rows-1), and from 0 to (cols-1). Thus, the element in the upper-left corner of the array is table[0][0]. It is not table[1][1] as you might expect from standard matrix notation.

    We can initialize a 2-dimensional array in the declaration statement as follows:

        int table[4][3] = { { 1, 2, 3},
                            { 4, 5, 6},
                            { 7, 8, 9},
                            {10,11,12} };
    
    The constant initializers do not need to be on separate lines, but this does allow us to visualize the array in 2D.
    1. Write a C program that declares and initializes an array as shown above, and then prints the array elements, in a 4x3 matrix format.

    2. Modify your program from the previous exercise, so that it also prints the sum of each row and the sum of each column in the array. You may use any format for this that you like, as long as it is convenient for checking your results.


This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~walker/courses/153.sp10/labs/lab-arrays-c.shtml

created Fall 2001, Fall 2002 by Alan Rosenthal, University of Toronto
revised Fall 2003, Fall 2004 by Tom Fairgrieve, University of Toronto
revised Fall 2004, Fall 2005 by Marge Coahran, University of Toronto
revised (with permission) January 2007-March 2008 by Marge Coahran, Grinnell College
revised April 2008 by Henry M. Walker
last revised 2 March 2010 by Henry M. Walker
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.