Functions

Source Code from Notes


Example 1

The following program uses a function to calculate the volume of the cube with the largest volume from the dimensions entered by the user for two cubes.


#include <stdio.h>


/* function declaration */
float cube_volume(float length, float height, float width);

/* main body of program */
main()
{
        float   length1,width1,height1,volume1;
        float   length2,width2,height2,volume2;

         /* input cube dimensions */
         printf("Enter dimensions of cube 1\n");
         scanf("%f %f %f",&length1,&height1,&width1);

         printf("Enter dimensions of cube 2\n");
         scanf("%f %f %f",&length2,&height2,&width2);

        /* calculate volume */
         volume1 = cube_volume(length1,height1,width1);
         volume2 = cube_volume(length2,height2,width2);

        /* output results */
        if (volume1 > volume2)
                printf("Cube 1 is largest, its volume is %f\n", volume1);
        else if (volume2 > volume1)
                printf("Cube 2 is largest, its volume is %f\n", volume2);
        else
                printf("both cubes have equal volumes of %f\n", volume1);
}


/* function definition */
float cube_volume(float length, float height, float width)
{
        float           volume;

        volume = length * width * height;
        return(volume);
}


Example - Recursion


/* Program to calculate the factorials of positive integers */
/* Program prints results for integers from 0 to 10         */
#include <stdio.h>

long factorial (int n);

main()
{
        int j;

        for (j=0;j < 11;j++)
                printf("%2d! = %ld\n",j,factorial(j));
}

long factorial (int n)
{
        long result;

        if (n==0)
                result = 1;
        else
                result = n * factorial(n-1);

        return(result);
}


Example

The following program prompts the user for the coordinates of 2 points. It then calculates the length of the line joining the two points.

#include <math.h>
#include <stdio.h>


struct coord {
        float    x,y,z;
};

float length (struct coord point1, struct coord point2);
float square (float x);

void main (void)
{
        struct coord p1,p2;
        float   line_length;

        printf("Enter coords of point 1 : ");
        scanf("%f       %f      %f",&p1.x, &p1.y,&p1.z);
        printf("Enter coords of point 2 : ");
        scanf("%f       %f      %f",&p2.x, &p2.y,&p2.z);

        line_length = length(p1,p2);
        printf("Length = %f\n",line_length);
}

float length (struct coord point1, struct coord point2)
{
        float   xlen,ylen,zlen;
        float   len_sqr;

        xlen = point1.x - point2.x;
        ylen = point1.y - point2.y;
        zlen = point1.z - point2.z;

        len_sqr = square(xlen) + square(ylen) + square(zlen);
        return (sqrt(len_sqr));
}

float square (float x)
{
        return ((x)*(x));
}


Back to Main Page for Lecture 6