CPS 202
Mount
Final Exam

Answers

Short Questions (5 points each, 100 total)

  1. List the three types of loops.
    while, for, do
  2. How many bits are in a byte?
    8
  3. How many bytes are in a short int?
    2
  4. What effect does adding the const keyword to a variable declaration have?
    The value assigned cannot be changed
  5. Name the two floating-point variable types.
    float, double
  6. Every C statement must end with what?
    ; (semicolon)
  7. What is enclosed by two curly braces?
    A block.
  8. The * (asterisk) character can be used for two things. What are they?
    multiplication, pointer indirection
  9. What does (!0) evaluate to?
    1
  10. What standard C function is used to terminate a program from anywhere in the program?
    exit()
  11. What function must every C program have?
    main
  12. What are the two boolean values?
    true and false (also accepted: 1 and 0)
  13. Name three things the preprocessor does.
    Includes header files (#include), expands macros (#define), strips comments, conditional compilation
  14. An array name is just like a pointer, but with one key difference - what is it?
    It cannot be assigned to (cannot be an lvalue)
  15. List all of the hexadecimal digits.
    0 1 2 3 4 5 6 7 8 9 A B C D E F
  16. What is the printf format for printing: An int? A char? A float? A long? An unsigned short?
    %d %c %f %ld %uh
  17. What is the name of \n? Of \t? Of \a? Of \r? Of \b?
    newline, tab, bell (alarm), carriage return, backspace
  18. When a function returns nothing, what is its return value in a prototype?
    void
  19. What operation does % perform?
    mod, modulus, or remainder
  20. Under what standard did the // comment type become a part of the C language?
    C99

Turn each of the following descriptions into C code. For example:
Declare an int variable called "speed": int speed;
(5 points each, 25 total)

  1. Declare a string named "address", for a length of 50.
    char address[51];
  2. Prototype a function called "double" that returns a long and takes a long parameter.
    long double(long);
    Technically, however, this is only a theoretical prototype, since "double" is a reserved keyword.
  3. Assign the address of an integer called count to an integer pointer called ptr.
    ptr = &count;
  4. Declare a static int variable named "count," initialized to -1.
    static int count = -1;
  5. Declare a function called volume that returns a float and take three floats, h, w, and d, as parameters.
    float volume(float h, float w, float d)

Each of the following individual lines was pulled from within large programs. Each has one or more bugs - fix them. (Note that because you don't have the context in which the line appears, some have more than one possible correct answer) (5 points each, 50 total)

  1. printf('Hello World!'); printf("Hello World!"); (must use "")
  2. int #_students; int num_students; (# not allowed in variable name)
  3. if (speed =< 65) printf("Speed is OK\n"); if (speed <= 65) printf("Speed is OK\n"); (=< is not valid)
  4. 4 = n; n = 4; (4 is an rvalue)
  5. int unsigned age; unsigned int age; (unsigned is a modifier and must be before int)
  6. #include <stdio.h>; #include <stdio.h> (no semicolon after an #include)
  7. auto static int area; static int area; (use either auto or static, but not both)
  8. unsigned int flag = -1; int flag = -1; (unsigned causes the -1 to be converted to an unsigned value) unsigned int flag = 1; (also accepted)
  9. &n = 6; *n = 6; (use the * operator, not the & operator, to assign a value to a pointer) n = 6; (also accepted)
  10. void timesplit(int total_minutes, int &hours, int &minutes);
    void timesplit(int total_minutes, int *hours, int *minutes); (use * for pointers, not &)

Long Questions - explain each in a full sentence or two (answer on a separate piece of paper - 10 points each)

  1. Explain the difference between floating point and integer variables. Include information on floating point and integer math.
    All C variables can be classified as either floating point (float and double) or integer (int and char). Simply, floating point variables can hold decimal places and integer variables cannot. Floating point variables are typically stored internally in IEEE format, and integers as straight bit patterns. In terms of math, everything works the same for both until division is used. Fractional values are retained when dividing floating point numbers - in integer division, fractional parts are dropped.
  2. What is the importance of indentation? Provide a small bit of C code where the lack of indentation could lead to confusion.
    Indentation, though ignored by the compiler, is crucial to the understanding of a program by a human. By properly and consistently indenting your code, you and others will be able to quickly (or, at least, more quickly) understand where loops and conditionals start and end.
     if (something == 1)
       printf("something is 1\n");
       printf("something is still 1\n");   // Appears to be part of the "if" but isn't
    
  3. What is the importance of commenting? Who benefits from comments?
    Commenting is also crucial to the understanding of a program or piece of code. While you're writing code, you're sure of what you're doing, but in the future, your logic may not be so clear. Comments allow you to understand what your point was in writing various pieces of code. Good commenting also helps others understand your program more quickly.
  4. What is meant by "operator precedence?" How do you force precedence?
    Operator precedence is the order in which the compiler decides to evaluate certain C operators. For example, multiplication is done prior to addition. If addition must be done before multiplication, precedence can be forced by adding parentheses to the statement.
  5. Explain the difference between static and automatic variables. Is there a default? When would you use one over the other? Static variables are variables that are local to a function, but which have a permanent storage location in memory that is retained between calls to the function. Automatic variables are also local, but their value is effectively destroyed after the function completes and recreated in memory each time the function is run. The default is automatic - the advantage to using static is the retention factor, whereas the advantage to auto is that the operating system may be able to manage automatic memory better.

Short Programming (answer on a separate piece of paper - 15 points each)

  1. Write this while loop as a for loop:
     x=0;
     while (x < 10) {
       printf("%d times 2 is %d\n",x,x*2);
       x++;
     }
     
      for (x=0; x < 10; x++)
        printf("%d time 2 is %d\n",x x*2);
     
  2. The area of a triangle is equal to ab/2, where a is the length of the base, and b is the height. Write a function to return the area of a triangle, given its base and height. Hint: because we're dividing, the function should return a float.
     float area_of_triangle(float length, float base)
     {
       float area;
       area = (length * base) / 2.0;
       return(area);
     }

Long Programming 1

You are attempting to catalog your book collection. In your first attempt at it, you decide to write a program to print a catalog sheet. The sheet will print 25 double-spaced rows of blanks to be filled in. To save space, you will print two separate columns of blanks. Your program must use at least one loop. Write the program to make the output look like this: (25 points)

                                   Book Catalog

    Author       Title       ISBN #           Author       Title       ISBN #

 1. ____________ ___________ _________   26.  ____________ ___________ _________

 2. ____________ ___________ _________   27.  ____________ ___________ _________

 3. ____________ ___________ _________   28.  ____________ ___________ _________
. . .

24. ____________ ___________ _________   49.  ____________ ___________ _________

25. ____________ ___________ _________   50.  ____________ ___________ _________
/* Rationale for this program:  This program illustrates many of the main
   points covered in the course.  It is the sort of minimum program I expect
   a student to be able to write.  It has an include, a variable, a loop,
   it uses printf formatting, math to calculate the item numbers, the
   increment operator, and logical testing.  It also forces you to think about
   how to solve the problem of getting lines into two columns as opposed to
   one long column.  It is not the most difficult exercise I've had you do,
   but it has all the elements of any program of substance, and shows how a
   little bit of code can go a long way to accomplishing important tasks.
*/

#include <stdio.h>

main()
{
  int i;
  printf("                                   Book Catalog\n\n");
  printf("    Author       Title       ISBN #           Author       Title       ISBN #\n\n");
  for (i=1; i<=25; i++)
    printf("%2d. ____________ ___________ ___________  "
           "%2d. ____________ ___________ ___________\n\n",
           i, i+25);

  return(0);
}

Long Programming 2

Your form works pretty well, but as you capture the data for printing, you find that different printers can fit more rows than others - and when you import the data into a word processing program, the double spacing is more trouble than it is worth. Modify the program to allow a variable number of rows, and to make double spacing optional, taking the data from prompts, using scanf to read the data. Allow a maximum of 60 rows. Here is a sample of a run of the program. (20 points)

c:\> bookform
Enter the number of rows to print: 70
 * Please enter a value from 1 to 60
Enter the number of rows to print: 40
Double space (y/n): U
 * Please enter either Y or N
Double space (y/n): N

                                   Book Catalog

    Author       Title       ISBN #           Author       Title       ISBN #

 1. ____________ ___________ _________   41.  ____________ ___________ _________
 2. ____________ ___________ _________   42.  ____________ ___________ _________
 3. ____________ ___________ _________   43.  ____________ ___________ _________
. . .
39. ____________ ___________ _________   79.  ____________ ___________ _________
40. ____________ ___________ _________   80.  ____________ ___________ _________
/* Rationale for this program: it is typical that a new program will be written
   based on old code.  Once a program is written, users find all sort of neat
   things they would like it to do.  Getting program parameters from the user is
   an extremely typical thing to do.  Proper testing of input data is critical
   to the success of many program, certainly any that get data from a user.
*/

#include <stdio.h>
#include <ctype.h>

main()
{
  int i;
  int linecount;
  char doublespace;
  int col2;

  while(1) {
    printf("Enter the number of rows to print: ");
    scanf("%d",&linecount);
    if (linecount < 1 || linecount > 60) {
      printf(" * Please enter a value from 1 to 60\n");
    }
    else break;
  }

  while(1) {
    printf("Double space (y/n): ");
    scanf(" %c",&doublespace);
    doublespace = toupper(doublespace);
    if (doublespace != 'N' && doublespace != 'Y') {
      printf(" * Please enter either Y or N\n");
    }
    else break;
  }

  col2 = linecount+1;

  printf("                                   Book Catalog\n\n");
  printf("    Author       Title       ISBN #            Author       Title       ISBN #\n\n");
  for (i=1; i<=linecount; i++, col2++) {
    printf("%2d. ____________ ___________ ___________  "
           "%3d. ____________ ___________ ___________\n",
           i, col2);
    if (doublespace == 'Y') printf("\n");
  }

  return(0);
}

Extra credit long program 1

Extra Credit 1

To make your program even more usable, you decide to rewrite it to accept the "lines" and "double" values on the command line. Here is a sample of a run of the program. (15 points)

c:\> bookform
usage: bookform lines double
  * please enter a value for lines (1-60)
  * please enter a value for double (Y or N)
c:\> bookform 50
usage: bookform lines double
  * please enter a value for double (Y or N)
c:\> bookform 100 N
usage: bookform lines double
  * lines value must be between 1 and 60
c:\> bookform 40 N

                                   Book Catalog

    Author       Title       ISBN #           Author       Title       ISBN #

 1. ____________ ___________ _________   41.  ____________ ___________ _________
 2. ____________ ___________ _________   42.  ____________ ___________ _________
 3. ____________ ___________ _________   43.  ____________ ___________ _________
. . .
39. ____________ ___________ _________   79.  ____________ ___________ _________
40. ____________ ___________ _________   80.  ____________ ___________ _________
/* Rationale for this program: this program has all the basic elements in the
   required program, and then expands on them.  Because we are now using the
   command line, we will have to use pointers, and because the data is provided
   in strings, we'll have to use the string libraries and string processing.
   A resourceful programmer will see the need for a function to handle errors.
   Aside from that, though, this version is very similar to version 2 above.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void usage(int, int, int, char *);

main(int argc, char *argv[])
{
  int i;
  int linecount;
  char doublespace;
  int col2;

  if (argc == 1) usage(1,1,0,"");
  if (argc == 2) usage(0,1,0,"");

  linecount = atoi(argv[1]);
  if (linecount < 1 || linecount > 60)
    usage(0,0,1,"  * lines value must be between 1 and 60\n");

  doublespace = toupper(argv[2][0]);
  if (doublespace != 'N' && doublespace != 'Y')
    usage(0,0,1,"  * double space value must be Y or N\n");

  col2 = linecount+1;

  printf("                                   Book Catalog\n\n");
  printf("    Author       Title       ISBN #            Author       Title       ISBN #\n\n");
  for (i=1; i<=linecount; i++, col2++) {
    printf("%2d. ____________ ___________ ___________  "
           "%3d. ____________ ___________ ___________\n",
           i, col2);
    if (doublespace == 'Y') printf("\n");
  }

  return(0);
}

void usage(int badcount, int baddouble, int badmsg, char *msg)
{
  printf("usage: bookform lines double\n");
  if (badcount == 1) printf("  * please enter a value for lines (1-60)\n");
  if (baddouble == 1) printf("  * please enter a value for double (Y or N)\n");
  if (badmsg == 1) printf("%s",msg);
  exit(1);
}

Extra credit long program 2

Writing stuff down is fine, but you decide it would be better to store your book collection data on disk. You're not exactly sure how to write database records to disk, so you decide to write a stub for the "write_data" function, but you can write the rest of the program. Make it look something like this (underlines indicate user input): (15 points)

New Book entry...
Enter Author's Name (blank to end): KN King
Enter Title: C Programming
Enter ISBN #: 0-393-96945-2
Saving "Supernatural" by "Everything" to database...

New Book entry...
Enter Author's Name (blank to end):
/* Rationale for this program:  this program again touches on all the basics,
   but also brings in the concept of progressive development, using a stub for
   a function we have not yet written.  It obviously includes functions, but
   also strings (and could use pointers, though it doesn't), and user
   interface.
*/

#include <stdio.h>

int get_line(char *);
int get_data(void);
int write_data(void);

main()
{

  while(1) {
    if (get_data() == 0) break;
  }

  return(0);
}


int get_data(void)
{
  char name[128];
  char title[128];
  char isbn[128];
  int ret;

  printf("New Book entry...\n");

  printf("Enter Author's Name (blank to end): ");
  ret = get_line(name);
  if (ret == 0) return(0);

  printf("Enter Title: ");
  get_line(title);

  printf("Enter ISBN #: ");
  get_line(isbn);

  printf("Saving \"%s\" by \"%s\" to database...\n\n",title,name);

  write_data();

  return(1);
}

// Read a single line of data, return length of data read
int get_line(char *buffer)
{
  int i=0;
  char ch;

  while((ch = getchar()) != '\n') {
    buffer[i] = ch;
    i++;
  }
  buffer[i] = '\0';
  return(i);
}

// Stub
int write_data(void)
{
  return(1);
}

Back to Main CPS 202 Page

Last Modified: 29 Apr 2002