COS 126
Exercise Set 2
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. Given the declarations int x; unsigned y; float z; what are the types of the following expressions?
    x + x
    x + y
    x/2.0
    y + 1
    z*10.0F
    y - 100.0F
    x - 2U
  2. What's wrong with the following program?
    int main(void) {
    	int i, n, sum;
    
    	printf("Enter n:\n");
    	scanf("%d", &n);
    	for (i = 1; i <= n; i++)
    		sum += i;
    	printf("Sum from 1 to %d = %d\n", n, sum);
    	return 0;
    }
  3. What value is printed by the following program?
    #include <stdio.h>
    int g = 11;
    
    int First(int i) {
    	int x = g%i;
    
    	g /= i;
    	return x;
    }
    
    int Second(int x, int r) { return g*x + r; }
    
    int main(void) {
    	int x, i = 3;
    
    	x = Second(i, First(i));
    	printf("%d\n", x);
    }
  4. What is printed by the following program? That is, what's in the array A?
    #include <stdio.h>
    
    int main(void) {
    	int i, A[6] = {11, 7, 5, 3, 1, -2};
    
    	for (i = 5; i > 0; i--)
    		if (A[i-1] > A[i]) {
    			int t = A[i-1]; A[i-1] = A[i]; A[i] = t;
    		}
    	for (i = 0; i < 6; i++)
    		printf("%d\n", A[i]);
    }

Answers

  1. int, unsigned, double, unsigned, float, float, unsigned.
  2. The #include <stdio.h> is missing, and sum is not initialized.
  3. 11.
  4. -2 11 7 5 3 1.

Copyright © 1996 David R. Hanson / drh@cs.princeton.edu
$Revision: 1.2 $ $Date: 1996/09/22 13:26:43 $