Wednesday, July 21, 2010

Functions example

#include <iostream>
using namespace std;

int cube(int);
void GetCube();
void PauseIt();
//array function
void CreateArray();
void FillArray(int[], int);
void DisplayArray(int[], int);
//pointer function
//first some simple functions
int add(int, int);
int subtract(int, int);
int multiply(int,int);
//the pointer function
void DoMath(int, int, int (*pFunction)(int,int));
void UseDoMath(); //use the pointer function

int main()
{
//GetCube();
//CreateArray();
UseDoMath();
PauseIt();


return 0;
}

int cube(int x)
{
return x * x * x;
}

void GetCube()
{
cout << "enter an int: " ;
int y;
cin >> y;
cout << endl;
//int myCube = cube(y);
cout << "the cube of " << y << " is " << cube(y) << endl;
}
void PauseIt()
{
cout<<endl;
cout <<"************************************" << endl;
cout << "Enter any character and press enter to exit" << endl;
char c;
cin >> c;
}

void CreateArray()
{
const int size=6;
int numbers[size];

FillArray(numbers, size);
}

void FillArray(int myArray[],int size)
{
for (int i=0;i<size;i++)
{
myArray[i]=i*7%2 +i;
}

DisplayArray(myArray,size);
}

void DisplayArray(int myArray[], int size)
{
int total=0;
for(int i=0; i < size;i++)
{
cout << myArray[i] << endl;
total+=myArray[i];

}
cout << "the total is " << total <<endl;
cout << "the average is " << double(total/size)<< endl;
}

int Add(int x, int y)
{
return x+y;
}

int Subtract(int x, int y)
{
return x-y;
}

int Multiply(int x, int y)
{
return x * y;
}

void DoMath(int x, int y, int (*pFunction)(int , int ))
{
cout << (*pFunction)(x,y) << endl;
cout << endl;
}

void UseDoMath()
{
int num1,num2;
cout << "enter the first number: ";
cin >> num1;
cout << endl;
cout << "Enter the second number: ";
cin >>num2;
cout << endl;

cout << "the sum is " ;
DoMath(num1, num2,Add);

cout << "The Difference is " ;
DoMath(num1,num2, Subtract);

cout << "The Product is " ;
DoMath(num1,num2, Multiply);

}

No comments:

Post a Comment