COMP 1917 Computing 1
Session 2, 2016

Tutorial - Week 5


Presentation Topic for Week 5

Explain Variable Scope in programming(C as an example). How can it be useful? How can it be dangerous? Some examples will be great.


  1. Write a C function
    void swap (int* first, int* second);
    
    which takes in pointers to two integers first and second which are declared in the calling function, and then swaps them around so that when swap returns first now has the value that second initially held, and second now has the value that first initially held.

  2. Explain what is the problem with the following function:
    void swap (int first, int second);
    
  3. Given these declarations
    int     n;
    int    *p, *q;
    double  x;
    double *r;
    
    What will happen when each of the following statements is executed (in order)? If any of them cause an error, explain why.
    a.  p = &n;
    b. *p =  5;
    c. *q = 17;
    d.  q =  p;
    e. *q =  8;
    f.  r = &x;
    g. *r = 3.0;
    h. *p = *r;
    i.  p =  r;
    j. *p =  n;
    k.  n =  x;
    
  4. Write a function
    double max_value(int n, double a[])
    
    which accepts a positive integer n as well as an array of n doubles, and returns the maximum of the n values in that array.

  5. Write a function
    int non_decreasing( int a[], int N )
    
    which takes an integer N together with an array a[] of N integers and checks to see whether the items in the array are sorted in non-decreasing order (i.e. a[i] ≥ a[i-1], for 0<i<N). Your function should returns 1 if the items are in non-decreasing order, 0 otherwise.

  6. Write a function
    int findIndex( int x, int a[], int N )
    
    which takes two integers x and N together with an array a[] of N integers and searches for the specified value x within the array. Your function should return the smallest index k such that a[k] is equal to x (or -1 if x does not occur in the array).

  7. Write a function
    int find_in_grid( int x, int grid[SIZE][SIZE], int size)
    
    that finds a special value in two dimensional array. You can use the stub code provided here to test it.

Presentation Topic for Week 6

Explore memory. Find out the number of bytes that C uses on your system to store the various types described below. Hint: You can use sizeof() function to print the number of bytes that given type uses(e.g printf("%lu\n", sizeof(int))
char, int, unsigned int, long long, unsigned long long, float, double
Are types signed or unsigned by default? What are the maximum and minimum values you can store in each of the types? What happens if you add 1 to the maximum value of a type, what happens if you subtract 1 from the minimum value of the type?