Monday, July 26, 2010

Further function examples

functionExamples.h


//function prototypes
//passing a pointer
int DestroyTokyo ( int * p);
void UseDestroyTokyo();
void PauseIt();
int * ReturnPointer();
//function overloading
double CalcPay(double rate, double hours);
double CalcPay(double salary);
double CalcPay(double rate, int pieces);

//default value
double CalculateTip(double amount, double percent=0.15);

//template
//void Add (Any a, Any b);


FunctionBodies.cpp
#include <iostream>
#include <string>
#include "functionExamples.h"
using namespace std;
int num2 = 8;

int DestroyTokyo(int * p)
{
int result=0;
if(*p > 5)
{
result=1;
}
return result;
}

void UseDestroyTokyo()
{
cout << "Enter a number: ";
int num;
cin >> num;
cout<< endl;
int * pdt=#
int dt=DestroyTokyo(pdt);

if (dt ==1)
{
cout << "Tokyo is destroyed" << endl;
}
else
{
cout<< "Tokyo is Safe " << endl;
}
}

void PauseIt()
{
cout << "enter any character and press Enter to exit"
<<endl;
char c;
cin >> c;
}

int * ReturnPointer()
{
//int num2=8;
num2=10;
int * ptr = &num2;
return ptr;
}

double CalcPay(double rate, double hours)
{
double pay;
if (hours > 40)
{
pay =rate*(40 + ((hours -40)*1.5));
}
else
{
pay=rate * hours;
}

return pay;
}

double CalcPay(double salary)
{
return salary / 52;
}

double CalcPay(double rate, int pieces)
{
return rate * pieces;
}

double CalculateTip(double amount, double percent)
{
return amount * percent;
}

//template <class Any>
//void Add (Any a, Any b)
//{
// cout << a + b << endl;
//}

Program.cpp

#include <iostream>
#include <string>
#include "functionExamples.h"
using namespace std;

int main()
{

/* int * p = ReturnPointer();
cout << p << " " << *p << endl;
UseDestroyTokyo();
cout << p << " " << *p << endl;*/
/* cout << "Enter the hourly rate " ;
double r;
cin >> r;
cout << "Enter the hours " ;
double hrs;
cin >> hrs;
cout << "Your weekly pay is " << CalcPay(r,hrs) << endl;
cout << "Enter your Annual Salary " ;
double s;
cin >> s;
cout << " Based on your salary your weekly pay is "
<< CalcPay(s) << endl;
cin.get();
cout << "Enter the rate per Piece ";
double rp;
cin >> rp;
cout << endl;
cout << "enter the number of pieces ";
int p;
cin>>p;
cout << "You get " << CalcPay(rp,p)
<< " for " << p << " pieces" <<endl;*/

/*cout << "Enter the Amount of the meal" ;
double amt;
cin >> amt;
cout << "Enter the percentage" ;
double perc;
cin >> perc;
cout << "the tip would be " << CalculateTip(amt, perc)
<< endl;*/


PauseIt();
}

Here is the template function that works
#include <iostream>
#include <string>

using namespace std;

template <class Any>
void Add(Any a, Any b)
{
cout << a + b << endl;
}

void PauseIt()
{
cout << "enter any character and press Enter to exit"
<<endl;
char c;
cin >> c;
}

int main()
{
int a=3,b=5;
Add(a,b);
double c=2.3, d=4.3;
Add(c,d);
cout << " enter the first word ";

string x, y;
getline(cin,x);
cout << endl;
cout << "Enter the second word ";
getline(cin, y);
Add(x,y);
PauseIt();
}

No comments:

Post a Comment