COMP 1917 Computing 1
Session 2, 2016

Tutorial Solutions - Week 2


  1. Introduce yourselves, get to know your tutor - how can you contact them?

  2. State briefly what each of the following Unix commands does:

  3. Which of the following are valid variable names in C? Which are not?

  4. Write a C program which allows the user to enter a number and then prints the square root of that number, to two decimal places.
      #include <stdio.h>
      #include <math.h>
    
      int main( void )
      {
        float x;
    
        printf("Enter a number: " );
        scanf( "%f", &x );
        printf("The square root of %1.2f is %1.2f\n", x, sqrt(x));
    
        return 0;
      }
    
  5. How would you modify your program so it computes the cube root instead of the square root? (Hint: use the pow() function, described here).

    replace sqrt(x) with pow( x, 1.0/3.0)
  6. Suppose you have written a C program and saved it to a file heron.c. What would you type on the UNIX command line to compile this program, producing the object file heron ? How would you then run this program?
       gcc -Wall -o heron heron.c
    
  7. Write a program which inputs the sidelengths a, b and c of a triangle, and computes the area of the triangle using Heron's formula:
       area = sqrt(s(s-a)(s-b)(s-c))
    
    where s is the "semi-perimeter"
       s = (a + b + c)/2.
    
      /*
         heron.c
    
         Use Heron's formula to compute the area of a triangle,
         given the side lengths.
      */
    
      #include <stdio.h>
      #include <math.h>
      // remember to compile with -lm
    
      int main( void )
      {
        float a,b,c; // sidelengths of a triangle
        float s;     // semi-perimeter
        float area;
    
        printf( "Enter sidelengths of a triangle:\n" );
    
        scanf( "%f", &a );
        scanf( "%f", &b );
        scanf( "%f", &c );
    
        // compute semi-perimeter
        s = ( a + b + c )/ 2;
    
        // compute area using Heron's formula
        area = sqrt(s*(s-a)*(s-b)*(s-c));
    
        printf( "Area = %1.2f\n", area );
    
        return 0;
      }