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 <iostream.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 
         cout << "Enter dimensions of cube 1\n";
         cin  >> length1 >> height1 >> width1;

         cout << "Enter dimensions of cube 2\n";
         cin  >> length2 >> height2 >> width2;

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

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


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


Additional Example - convert Train Timetable from Iteration Tutorial to use functions


// Calculate train time table - using functions

#include <isotream.h>

//Function declarations
int     to_24hr(int mins);
int     to_mins(int hr_24);

main()
{
        const int wait = 5;
        int     start, stop, time;
        int     start_min, stop_min;
        int     journey_time, freq_time;
        int     dep_red,dep_green,dep_yellow,arr_blue;
        int     dep_red_min,dep_green_min,dep_yellow_min,arr_blue_min;

        cout << "Enter the journey time (minutes)\n";
        cin >> journey_time;

        cout << "Enter the first train time\n";
        cin >> start;

        cout << "Enter the last train time\n";
        cin >> stop;

        cout << "Enter the frequency time\n";
        cin >> freq_time;

        // convert start and stop times to minutes
        start_min = to_mins(start);
        stop_min = to_mins(stop);

        // table header
        cout << "RED \t GREEN \t YELLOW \t BLUE\n";

        for (time=start_min; time<=stop_min; time+=freq_time)
        {
                // Calculate Times 
                dep_red_min = time;
                dep_green_min = (time + journey_time + wait);
                dep_yellow_min = (time + 2*(journey_time + wait));
                arr_blue_min = time + 3*journey_time +2*wait;

                // Convert times to 24 hour clock to display 
                dep_red = to_24hr(dep_red_min);
                dep_green = to_24hr(dep_green_min);
                dep_yellow = to_24hr(dep_yellow_min );
                arr_blue = to_24hr(arr_blue_min);

                cout << dep_red << "\t" << dep_green << "\t"
                     << dep_yellow << "\t" << arr_blue << "\n";
        }
} // end of main program 

// Definition of to_24hr function 
int     to_24hr(int mins)
{
        int     hr, min, total;
        hr = mins/60;
        min = mins%60;
        total = hr*100 + min;

        return (total);
}

// Definition of to_mins function 
int     to_mins(int hr_24)
{
        int hr, min, total_mins;

        hr = hr_24/100;
        min = hr_24%100;
        total_mins = hr*60 + min;

        return(total_mins);
}


Example - Recursion


// Program to calculate the factorials of positive integers 
// Program prints results for integers from 0 to 10        

#include <iostream.h>

long factorial (int n);

main()
{
        int j;

        for (j=0;j < 11;j++)
                cout << j << "! = " << factorial(j) << "\n";

}

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 <iostream.h>


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

// function declarations
float length (coord point1, coord point2);
float square (float x);

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


        cout << "Enter coords of point 1 : ";
        cin >> p1.x >> p1.y >> p1.z;

        cout << "Enter coords of point 2 : ";
        cin >> p2.x >> p2.y >> p2.z;

        line_length = length(p1, p2);
        cout << "Length = " << line_length << "\n";
}


float length (coord point1, 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));
}


Example - Reference Variables

This example illustrates how reference variables can be used to permit a function to change values in the calling program.


#include <iostream.h>
void swap(int &ra, int &rb);

main()
{
        int a,b;

        a = 10;
        b = 12;
        swap (a,b);
}
void swap(int &ra, int &rb)
{
        int temp;

        temp = ra;
        ra   = rb;
        rb   = temp;
}


Example

This example sends an array to the function. The function then calculates both the largest and smallest value stored in the array. These maximum and minimum values stored are then returned to the main calling program as function arguments.

There is a msitake in the notes, the following program is correct and has made MAX be global so the function also knows its value. An alternative solution is given below where MAX is local and is sent to the function.


#include <iostream.h>
#include <math.h>

void max_min(float &max, float &min, float array[]);

const int MAX = 5;

main()
{
        float array1[MAX];
        float array2[MAX];
        float   max1, min1;

        float   max2, min2;
        int     i;

        for (i=0; i<MAX;i++)
        {
                cout << "Enter value  "<< i << " of array1\n";
                cin >> array1[i];
        }
        for (i=0; i<MAX;i++)
        {
                cout << "Enter value  "<< i << " of array2\n";
                cin >> array2[i];
        }

        max_min(max1,min1,array1);
        max_min(max2,min2,array2);

        cout << "Array 1 : max = " << max1 << " min = " << min1 << "\n";
        cout << "Array 2 : max = " << max2 << " min = " << min2 << "\n";
}

void max_min(float &max, float &min, float array[])
{
        int     i;

        min = array[0];
        max = array[0];

        for (i=1;i < MAX;i++)
        {
                if (array[i] > max)
                        max = array[i];
                if (array[i] < min)
                        min = array[i];
        }
}


Alternative Solution


#include <iostream.h>
#include <math.h>

void max_min(int size_array, float &max, float &min, float array[]);


main()
{
	const int MAX = 5;
        float array1[MAX];
        float array2[MAX];
        float   max1, min1;

        float   max2, min2;
        int     i;

        for (i=0; i<MAX;i++)
        {
                cout << "Enter value  "<< i << " of array1\n";
                cin >> array1[i];
        }
        for (i=0; i<MAX;i++)
        {
                cout << "Enter value  "<< i << " of array2\n";
                cin >> array2[i];
        }

        max_min(MAX, max1,min1,array1);
        max_min(MAX, max2,min2,array2);

        cout << "Array 1 : max = " << max1 << " min = " << min1 << "\n";
        cout << "Array 2 : max = " << max2 << " min = " << min2 << "\n";
}

void max_min(int size_array, float &max, float &min, float array[])
{
        int     i;

        min = array[0];
        max = array[0];

        for (i=1;i < size_array;i++)
        {
                if (array[i] > max)
                        max = array[i];
                if (array[i] < min)
                        min = array[i];
        }
}

Example - Sports Timer

A sports timer can time an event returning the elapsed time in seconds. Write a function to convert the time in seconds to hours, minutes and seconds, returning these values as function arguments. The function should be called from a main calling program where the user is prompted to enter the elapsed time in seconds.

Reference variable must be used in the function arguments for hours, minutes and seconds.


#include <iostream.h>
#include <math.h>


// Function Declaration
void change_time(int elapsed_seconds, int &hours, int &mins, int &seconds);

main()
{
        int     elapsed_time;
        int     time_hours, time_minutes, time_seconds;


        cout << "Enter the time for the event\n";
        cin >> elapsed_time;

        //Function call - send address of variables to change 
        change_time(elapsed_time, time_hours, time_minutes, time_seconds);


        // Use variables as normal 
        cout << "The number of hours is " << time_hours << " \n";
        cout << "The number of minutes is "<< time_minutes << " \n";
        cout << "The number of seconds is " << time_seconds << " \n";
        cout << "The number of seconds is " << time_seconds << " \n";

}

// Function to convert total in seconds to hours, mins and seconds 
void change_time(int elapsed_seconds, int &hours, int &mins, int &seconds)
{
        int     tmp_minutes;

        seconds = elapsed_seconds%60;

        tmp_minutes = elapsed_seconds/60;

        mins = tmp_minutes%60;

        hours =  tmp_minutes /60;
}


Back to Main Page for Lecture 6