Tutorial 6

Let's get functional!

Okay, you've completed the last program. You have seen how I changed things around and made it easier to implement than was first expected. You understand the code! Now it's time to get into the good stuff. A program like the previous one is fine if it does no more than that but in real life we need more from our applications. BASIC programmers will be familiar with "sub routines". These are like mini programs that run inside a full program. In C++ we have the same notion, except we call them functions. A function can accept parameters or not. Every function will always return to the position that initially called it and continue on from there. Believe it or not, every C++ program that I have shown you so far has a function in it. You might not have already known it but "void main(void)" is a function. It is the main function of the program. Every program needs a main function to act as the driver for the program and get things under way. The function "void main(void)" has the following meaning. The first void means that the function has no return value or it does not return anything. The main is the name of the function and the second void means that the function takes no parameters.


Every function that you write must consist of at least three things. Firstly it must have a function "prototype". A prototype is like a function declaration. It is the same as the function header, e.g. void some_func(void), except you must place a semi-colon after the last bracket. These prototypes are usually placed before the main function. The main function itself does not need this prototype as it is understood by the compiler. Prototypes don't need variable names when specifying the type of parameter, e.g. int some_func(int); Here we see that the some_func function takes an int as a parameter and returns an int back. Secondly the function must have its body. This is where all the functions code is placed. It looks just like another main function, in its layout. Finally the function must have a call to it somewhere in the code or it will never be accessed. A function call is simply the function name with the name of the variable(s) being passed as parameter(s) in brackets after the name and ended with a semi-colon, e.g. some_func(number); If the function returns a value then we will need to have a variable to store this value, e.g. res = some_func(num);


This may take a little while to get used to but the benefits far outweigh the learning. With functions we can write much bigger programs with less complexity and the same function can be used many times and for different things so the amount of code actually written is reduced too. Also it is much simpler to track down problems and debug your code when using functions because they are much smaller than the entire code wrapped into one main function. So with all that in mind and a good knowledge of functions from your reference book, we shall begin. Yet again I have chosen our payroll system to show some functions in action. In fact I have made the whole program work in functions and of course I have thrown in some more presentation alterations for the visual finish. If you want to know more drop me a line and I'll do my best to reply to your request for information. redsetter@eircom.net




//So here we are again with our payroll system. It's getting more and more refined
//by the minute and when this program is finished it will start to look quite
//impressive, from both a visual and a code point of view. By now you should be
//used to some of the basic things so I have stopped commmenting unnessecarily. I
//hope that you understand this one as it will lead to a good foundation for your
//future programming tasks.

//pre-processor directives
#include <iostream.h>
#include <stdlib.h>
#include <iomanip.h>
#include <conio.h>

//function prototypes
int chkCode(char, int[]);
int isValid(char);
int calMan(int&);
int calHrly(int&);
int calComm(int&);
int calPce(int&);
void calNett(float);
int showTable(int[], int);

void main(void)
{
	//declaration and initialisation of variables
	int workers[4]={0}, status=1;
	char code;

	//use of sentinel to keep loop going until user wishes to stop
	while(status != 0)
	{
		//selection table
		cout<<"\n\n\n\n\n\n"
			 <<"\t\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
			 <<"\t\tEnter m for manager.\t\n"
			 <<"\t\tEnter h for hourly worker.\t\n"
			 <<"\t\tEnter c for commission worker.\t\n"
			 <<"\t\tEnter p for piecerate worker.\t\n"
			 <<"\t\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n"
			 <<"\t\tEnter code (x to end): ";
		cin>>code;

		status = chkCode(code, workers);
	}
}

int chkCode(char code, int workers[])
{
	if(isValid(code))
	{
		//to determine which worker to pay
		if(code == 'm')
			return(calMan(workers[0]));

		else if(code == 'h')
			return(calHrly(workers[1]));

		else if(code == 'c')
			return(calComm(workers[2]));

		else if(code == 'p')
			return(calPce(workers[3]));

		else if(code == 'x')
		{
			//calculates total of array and hence workers paid
			int numWorkers = workers[0] + workers[1] + workers[2] + workers[3];
			return(showTable(workers, numWorkers));
		}
	}

	else
	{
		clrscr();
		cout<<"\n\t\tInvalid code. Enter a correct code!";
	}

	return 1;
}

int isValid(char code)
{
	int codeChk[5]={'m', 'h', 'c', 'p', 'x'};

	for(int i=0; i<5; i++)
	{
		if(code == codeChk[i])
			return 1;
	}

	return 0;
}

int calMan(int &man)
{
	float gross=0;

	clrscr();
	cout<<"\n\n\n\n\n\n\t\tManager selected.\n\n\n"<<"\t\tEnter salary: ";
	cin>>gross;
	cout<<"\n\t\tThe managers gross pay is: "<<gross<<endl;
	calNett(gross);
	man++;
	return 1;
}

int calHrly(int &hrly)
{
	float gross=0, hrPay=0, numHrs=0;

	clrscr();
	cout<<"\n\n\n\n\n\n\t\tHourly worker selected.\n\n\n"<<"\t\tEnter no. of hours worked: ";
	cin>>numHrs;
	cout<<"\t\tEnter pay per hour: ";
	cin>>hrPay;

	if(numHrs > 40)
		gross=((numHrs - 40) * (1.5 * hrPay)) + (40 * hrPay);

	else
		gross=numHrs * hrPay;

	cout<<"\t\tThe hourly workers gross pay is: ";
	cout<<setprecision(2)<<setiosflags(ios::fixed | ios::showpoint)<<gross<<endl;
	calNett(gross);
	hrly++;
	return 1;
}

int calComm(int &comm)
{
	float gross=0, wkSales=0;

	clrscr();
	cout<<"\n\n\n\n\n\n\t\tCommission worker selected.\n\n\n"<<"\t\tEnter gross weekly sales: ";
	cin>>wkSales;
	gross =(wkSales * .57) + 250;
	cout<<"\t\tThe commission workers gross pay is: ";
	cout<<setprecision(2)<<setiosflags(ios::fixed | ios::showpoint)<<gross<<endl;
	calNett(gross);
	comm++;
	return 1;
}

int calPce(int &pce)
{
	float gross=0, pcePay=0;
	int numPces=0;

	clrscr();
	cout<<"\n\n\n\n\n\n\t\tPiece-rate worker selected.\n\n\n"<<"\t\tEnter no. of pieces: ";
	cin>>numPces;
	cout<<"\t\tEnter pay per piece: ";
	cin>>pcePay;
	gross=numPces * pcePay;
	cout<<"\t\tThe piece-rate workers gross pay is: ";
	cout<<setprecision(2)<<setiosflags(ios::fixed | ios::showpoint)<<gross<<endl;
	calNett(gross);
	pce++;
	return 1;
}

void calNett(float gross)
{
	float nett=0, tax=0, taxable=0;

	//calculation of tax
	if(gross < 100)
		nett = gross;

	else
	{
		taxable = gross - 100;

		if(taxable >= 150)
			tax = ((taxable - 150) * .48) + (150 * .27);

		else
			tax = taxable * .27;

		nett = gross - tax;
		cout<<"\t\tThe workers net pay is: ";
		cout<<setprecision(2)<<setiosflags(ios::fixed | ios::showpoint)<<nett<<"\n\n\n";
	}
}

int showTable(int a[], int numWorkers)
{
	//clear the screen to display the table
	clrscr();
	//table of total no of workers paid using array
	cout<<"\n\n\n\n\n\n\tTotal number of managers paid:"
		 <<setw(21)<<setiosflags(ios::right)<<a[0]<<endl;
	cout<<"\tTotal number of hourly workers paid:"
		 <<setw(15)<<setiosflags(ios::right)<<a[1]<<endl;
	cout<<"\tTotal number of commission workers paid:"
		 <<setw(11)<<setiosflags(ios::right)<<a[2]<<endl;
	cout<<"\tTotal number of piece-rate workers paid:"
		 <<setw(11)<<setiosflags(ios::right)<<a[3]<<endl;
	cout<<"\tThe total number of workers paid is:"
		 <<setw(15)<<setiosflags(ios::right)<<numWorkers<<endl;
	return 0;
}


So, there we have it, a good program that is fully functional, has lots of error detection and is broken down nicely into simple functions so as to improve its readibility and future development. If you had no problems with this one then you are positively flying with this language and should move on immeadiately to something else so as to further your skills. If however you had a few problems then don't worry as this is a difficult enough topic for first-timers and it will become second nature with practice.


Previous Index Next


© Redsetter 2000