COS 126
Exercise Set 1
Answers

These exercises are intended to guide class discussion and to help review some of the course material in preparation for the two midterms. Do not turn in solutions.

  1. What does the following sequence of three C statements do? t = x; x = y; y = t;
  2. What is wrong with the following C statement? if (a > b) then c = 0;
  3. What is wrong with: if a > b { c = 0; }
  4. What is wrong with: if (a > b) c = 0;
  5. What is wrong with the following C program fragment?

    c = 0
    b = 0;

  6. What is wrong with: if (a > b) c = 0 else b = 0;
  7. Write a C program that prints the multiplication table from 1 to 9, that is, each number from 1 through 9 multiplied by each number from 1 through 10.
  8. What value is printed by the following program?
    #include <stdio.h>
    int f(int x) { return x + 2; }
    
    int main(void) {
    	int x;
    
    	x = 4;
    	printf("%d\n", f(x + 2));
    	return 0;
    }
  9. Try running the following program through the lcc compiler to see what error messages it produces for semicolon errors.
    int square (int x);
    	{ return x*x; }
    
    int main(void) {
    	int a, b, c;
    
    	c = 0
    	b = 0;
    	if (a > b) c = 0 else b = 0;
    	return 0;
    }

Answers

  1. Exchanges the values of x and y.
  2. There's no then keyword in C.
  3. The condition in if statements (and while statements) must be enclosed in parentheses .
  4. Nothing; this one is OK.
  5. Missing semicolon at the end of the first expression statement.
  6. Missing semicolon after the expression statement c = 0.
  7. #include <stdio.h>
    
    int main(void) {
    	int i, j;
    
    	for (i = 1; i <= 9; i++) {
    		for (j = 1; j <= 10; j++)
    			printf("%3d", i*j);
    		printf("\n");
    	}
    	return 0;
    }
  8. 8.

Copyright © 1996 David R. Hanson / drh@cs.princeton.edu
$Revision: 1.3 $ $Date: 1996/09/10 21:28:10 $