Sample Midterm

  1. What are all possible outputs of the following code fragment?
    void f(int a, int b)
    {
    		printf("%d %d\n", a, b);
    }
     
    void main(void)
    {
    		int i = 5;
    		f(++i, ++i);
    }
    
  2. Given the definitions
    		int numbs[10];
    		int *ptr = numbs;
    
    which of the following are equivalent, and why?
    1. numbs[3]
    2. numbs + 3
    3. * ( numbs + 3 )
    4. * ( ptr + 3 )
    5. *ptr + 3
  3. Write a recursive function to add the integers from a to b. You may assume that a ≤ b initially.
  4. Use the following code fragment to answer parts a, b, and c:
    for(x = i = 0; i <= 100; i += 2, x += i);
    
    1. In one short sentence , what does this for loop do?
    2. Is the following while loop equivalent? If not, how does its result differ?
      		x = i = 0;
      		while( i++ = 100)
      			x += ++i;
      
    3. Does the following for loop do the same thing? If not, what does it do?
      		for(x = i = 0; i <= 100; i++){
      			if (!(i % 2))
      				continue;
      			x = x + i;
      		}
      
  5. What does the following function do?
    		int x(char *s, char *t)
    		{
    			for( ; *s == *t; s++, t++)
    				if (*s == '\0')
    					return(0);
    			return(*s - *t);
    		}
    
  6. What does this function do?
    char *x(char *s, char c)
    {
    		char *r = NULL;
     
    		do{
    			while(*s && *s != c) s++;
    			if (*s) r = s; 
    		} while(*s++);
    		return(r);
    }
    
  7. The following segment of code is supposed to print the number of times the routine a_again is called. Yet, regardless of the input, it prints 0. Why? How would you fix it?
    void a_again(int acount)
    {
    		++acount;
    }
     
    void main(void)
    {
    		register int c;
    		int counter = 0;
     
    		while((c = getchar()) != EOF)
    					if (c == 'a' || c == 'A')
    				a_again(counter);
     
    		printf("%d\n", counter);
    		exit(0);
    }
    

ECS 153, Introduction to Computer Security
Winter Quarter 2002
Email: cs153@cs.ucdavis.edu