Week 2 Tutorial — C Refresher

  1. (Loops)
    1. The factorial of a positive number n, written n!, is defined as follows:

      • 1! = 1
      • n! = n * (n-1)!  for n > 1

      For example, 4! = 4*3*2*1 = 24.

      Write a for-loop to compute the factorial of a given natural number n.

    2. Write a function

      int gcd(int a, int b) {
         ...
      }
      

      that uses a while-loop to implement Euclid's algorithm for computing the greatest common divisor ("gcd") of two natural numbers:

      • Replace the larger of the two numbers by their difference.
      • Stop when the two numbers are equal — this is the gcd.

      Example: 
       
       
       
       
       
       
       
       
      gcd(651,378) = 21 
      ab
      651378
      273378
      273105
      168105
      63105
      6342
      2142
      2121

  2. (Arrays, Strings)

    1. What is the output of the following program?

       1  #include <stdio.h>
       2
       3  int main(void) {
       4     int arr[4] = {10,10,10,10};
       5     char str[] = "Text";
       6     int i;
       7
       8     for (i = 1; i < 4; i++) {
       9        arr[i] = arr[i-1] + arr[i] + 1;
      10        str[i] = str[i+1];
      11     }
      12     printf("Val[3] = %d\n", arr[3]);
      13     printf("String = \"%s\"\n", str);
      14     return 0;
      15  }
      

    2. What is the purpose of the program statement in line 14?

  3. (Input/Output) Write program statements, including variable declarations, to

    1. ask the user for an integer, read the integer, and output it;
    2. ask the user for a floating point number, read the number, and output it;
    3. ask the user for a string, read the string, and output it.
  4. (Files) Write program statements, including variable declarations, to

  5. (Pointers) What is the output of the following program?

     1  #include <stdio.h>
     2
     3  int main(void) {
     4     int *ptr1, *ptr2;
     5     int i = 10, j = 20;
     6
     7     ptr1 = &i;
     8     ptr2 = &j;
     9
    10     *ptr1 = *ptr1 + *ptr2;
    11     ptr2 = ptr1;
    12     *ptr2 = 2 * (*ptr2);
    13     printf("Val = %d\n", *ptr1 + *ptr2);
    14     return 0;
    15  }