CS29003 Algorithms Laboratory Autumn/Spring semester

Miscellaneous information for students


Every file (.c or .h) should start with a comment of few lines.

   /* Name: Fibonacci.c
      Creator: Foolan Barik (foobar@iitkgp.ac.in)
      Date: July 24, 2007
      Description: In this file 108 ways of computing Fibonacci numbers are implemented

Every function should also be preceded by a comment of few lines.

   /* Name: linearDnC()
      Input: n - a non-negative integer
      Output: The n-th Fibonacci number F(n)
      Description: This program uses a divide-and-conquer recursion for
         computing Fibonacci numbers in linear time. It is based on the
         formula: F(m+n) = F(m+1)F(n)+F(m)F(n-1).
   int linearDnC ( int n )
       int t1, t2, t3; /* Temporary variables storing smaller Fibonacci numbers */
       /* n must be non-negative */
       if (n < 0) return -1;
       /* Basis cases */
       if (n == 0) return 0;
       if (n == 1) return 1;
       if (n == 2) return 1;
       /* Recursive calls on two subproblems of half size */
       t1 = linearDnC(n/2);
       t2 = linearDnC(n/2+1);
       /* Case 1: n is odd */
       if (n & 1) return t1*t1+t2*t2;
       /* Case 2: n is even */
       t3 = t2 - t1;
       return t1*(t2+t3);

Put comments elsewhere also in order to enhance the legibility of your code. It is not advisable to flood your program with comments. For example, you have no need to write

/* increment i */
against ++i;. That is obvious! Mark important points only. For an example, look at the comments given in the above function.


You should learn how to indent a C program. Properly indented programs are legible, promote easier debugging and provide protection against certain queer compilation errors. In this article, the Kernighan-Ritchie style of indentation is followed. Click here for more information.

Indentation does not only mean that a few lines of your code leave extra blank spaces on their left. Certain conventions regarding these spaces are necessary for this indentation to be a proper indentation. This also includes proper placement of the curly braces ({ and }). A sequence of C statements enclosed within a matching pair of braces is called a block.

Fix an indentation amount for your codes. In industry, people usually use a tab as the indentation amount. Since a tab (normally) means eight characters, programs with large levels of nesting of blocks may face difficulty with such a large indentation amount. You may instead use 3 or 4 spaces as the indentation amount.

Lab home My home