Assignment #5

Introductory C Programming

UW Experimental College


Assignment #5

Handouts:

Assignment #5
Answers to Assignment #4
Class Notes, Chapter 9
Class Notes, Chapter 10

Reading Assignment:

Class Notes, Chapter 9

Review Questions:

  1. What's wrong with this #define line?
    	#define N 10;
    
  2. Suppose you defined the macro
    	#define SIX 2*3
    
    Then, suppose you used it in another expression:
    	int x = 12 / SIX;
    
    What value would x be set to?
  3. If the header file x.h contains an external prototype declaration for a function q(), where should x.h be included?
  4. (harder) How many differences can you think of between i and J as defined by these two lines?
    	int i = 10;
    	#define J 10
    
    (Hint: think about trying to write J = 5, or int a[i].)


Exercises:

  1. Pick one of the programs we've worked with so far that uses the getline function, such as the getline test program (assignment 4, exercise 2) or the ``word zipping'' program (assignment 4, tutorial 3) or the checkbook balancing program (assignment 4, exercise 6). Arrange the program in two source files, one containing main(), and one containing getline(). If possible, set your compiler to warn you when functions are called or defined without a prototype in scope. Create a header file getline.h containing the external function prototype for getline(), and #include it as you see fit. Also use a preprocessor macro such as MAXLINE for the maximum line length (i.e. in declarations of line arrays, and calls to getline).
  2. Write a program to read its input and write it out, double-spaced (that is, with an extra blank line between each line). Process the input a character at a time; do not read entire lines at a time using getline.
  3. Write the function
    	int countchars(char string[], int ch);
    
    which returns the number of times the character ch appears in the string. For example, the call
    	countchars("Hello, world!", 'o')
    
    would return 2.
  4. Write a short program to read two lines of text, and concatenate them using strcat. Since strcat concatenates in-place, you'll have to make sure you have enough memory to hold the concatenated copy. For now, use a char array which is twice as big as either of the arrays you use for reading the two lines. Use strcpy to copy the first string to the destination array, and strcat to append the second one.
  5. Write the function
    	replace(char string[], char from[], char to[])
    
    which finds the string from in the string string and replaces it with the string to. You may assume that from and to are the same length. For example, the code
    	char string[] = "recieve";
    	replace(string, "ie", "ei");
    
    should change string to "receive".

    (Extra credit: Think about what replace() should do if the from string appears multiple times in the input string.)


This page by Steve Summit // Copyright 1995-9 // mail feedback