Here are a couple of silly functions that show the use of Function pointers and templates. Function pointers are pointers to functions with a particular signature. In our case the function points to any function that returns and integer and takes two integer values. Pointer functions are closely related to Delegates in C#.
Templates are called Generics in C# and Java. they are functions or classes whose data type is not determined until run time. Both of these tools can prove a valuable way to manage code for scalability and flexibility.
We used three files. First I will show the header file. This file contains all the function prototypes and the complete template function. You cannot separate a template function's implementation from its type declaration.
AdvancedFunctions.h
int Add(int, int);
int Subtract(int, int);
int Multiply(int, int);
int Divide(int, int);
void DoMath(int, int, int(*pfunction)(int, int));
template <typename any>
void Addition(any a, any b)
{
cout << a + b << endl;
}
Here is the Function definition file:
FunctionDefinitions.cpp
#include <iostream>
#include "AdvancedFunctions.h"
using namespace std;
int Add (int n1, int n2)
{
return n1+n2;
}
int Subtract(int n1,int n2)
{
return n1-n2;
}
int Multiply(int n1, int n2)
{
return n1*n2;
}
int Divide(int n1, int n2)
{
int quotient=0;
if (n2 !=0)
{
quotient=n1/n2;
}
return quotient;
}
void DoMath(int n1, int n2, int(*pfunction)(int , int ))
{
cout << pfunction(n1,n2) << endl;
}
And lastly, here is the Program file with the main:
Program.cpp
#include <iostream>
#include "AdvancedFunctions.h"
#include <string>
using namespace std;
int main()
{
DoMath(5,7,Add);
cout << endl;
DoMath(13,4,Subtract);
cout << endl;
DoMath(13,4,Multiply);
cout << endl;
DoMath(13,4,Divide);
Addition(6,7);
Addition(4.3345,13.567);
string x = "hello";
string y="World";
Addition(x,y);
char c;
cin >> c;
}
Monday, July 25, 2011
Chapter 6_9
Here is the Chapter 6 9 assignment. Fist a screen shot of the program running then the text file:
4
Sam Stone
2000
Freida Class
100500
Tammy Tubbs
5000
Red Raptor
55000

Here is the code
#include <iostream>
#include<fstream>
#include <string>
using namespace std;
struct Contributors
{
string name;
double amount;
};
const double GRAND= 10000;
void GetContributors()
{
int number=0;
fstream patrons("C:\\Users\\sconger\\Desktop\\donors.txt", ios::in | ios::app);
patrons >> number;
cout << "The number of contriburtors is " << number << endl;
patrons.ignore();
Contributors * donorList = new Contributors[number];
while (!patrons.eof())
{
for(int i=0;i<number;i++)
{
getline(patrons,donorList[i].name);
patrons>>donorList[i].amount;
patrons.ignore();
}
patrons.ignore();
}
patrons.close();
cout << "Grand Patrons" << endl;
cout << "****************************"<<endl;
for(int i=0;i<number;i++)
{
if(donorList[i].amount >= GRAND)
{
cout << donorList[i].name << "\t\t" << donorList[i].amount << endl;
}
}
cout << "Patrons" << endl;
cout << "****************************"<<endl;
for(int i=0;i<number;i++)
{
if(donorList[i].amount < GRAND)
{
cout << donorList[i].name << "\t\t" << donorList[i].amount << endl;
}
}
delete[] donorList;
}
int main()
{
GetContributors();
char c;
cin >> c;
}
4
Sam Stone
2000
Freida Class
100500
Tammy Tubbs
5000
Red Raptor
55000
Here is the code
#include <iostream>
#include<fstream>
#include <string>
using namespace std;
struct Contributors
{
string name;
double amount;
};
const double GRAND= 10000;
void GetContributors()
{
int number=0;
fstream patrons("C:\\Users\\sconger\\Desktop\\donors.txt", ios::in | ios::app);
patrons >> number;
cout << "The number of contriburtors is " << number << endl;
patrons.ignore();
Contributors * donorList = new Contributors[number];
while (!patrons.eof())
{
for(int i=0;i<number;i++)
{
getline(patrons,donorList[i].name);
patrons>>donorList[i].amount;
patrons.ignore();
}
patrons.ignore();
}
patrons.close();
cout << "Grand Patrons" << endl;
cout << "****************************"<<endl;
for(int i=0;i<number;i++)
{
if(donorList[i].amount >= GRAND)
{
cout << donorList[i].name << "\t\t" << donorList[i].amount << endl;
}
}
cout << "Patrons" << endl;
cout << "****************************"<<endl;
for(int i=0;i<number;i++)
{
if(donorList[i].amount < GRAND)
{
cout << donorList[i].name << "\t\t" << donorList[i].amount << endl;
}
}
delete[] donorList;
}
int main()
{
GetContributors();
char c;
cin >> c;
}
Thursday, July 21, 2011
XML, XSLT and ASP.Net
Here is the example we did in class. First we created the XSLT document. The XSLT document is designed to take an XML document and transform it into some other kind of document--in our case an html document. Here is a picture of the web page running:

Here is the code for the XSLT:
memo.xslt
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
xmlns="http://www.w3.org/1999/xhtml" xmlns:m ="http://www.spconger.com/memo" >
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<h2>Automart Memo</h2>
<hr/>
<p>
<strong>To: </strong>
<xsl:value-of select="m:memo/m:header/m:to"/>
</p>
<p>
<strong>From: </strong>
<xsl:value-of select="m:memo/m:header/m:from"/>
</p>
<p>
<strong>Date: </strong>
<xsl:value-of select="m:memo/m:header/m:date"/>
</p>
<p>
<strong>About: </strong>
<xsl:value-of select="m:memo/m:header/m:about"/>
</p>
<hr/>
<xsl:for-each select="//m:memo/m:body/m:p">
<p>
<xsl:value-of select="."/>
</p>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
We started a new empty Web Site in visual Studio. We added a new web form and then added an existing item--the XSLT document. Here is the code for the Web Form. We added a GridView, a button and an XML control. For the Gridview we also added a new column which was a button, (type link, command Select, text Select) Most of the other markup for the web grid is just formatting and could be left out.
Default.Aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4">
<Columns>
<asp:ButtonField CommandName="Select" Text="Select" />
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Get memo"
onclick="Button1_Click" />
<asp:Xml ID="Xml1" runat="server"></asp:Xml>
</div>
</form>
</body>
</html>
In the code behind we used basic ADO. We needed to Add the System.Data, System.Data.SqlClient and the System.Xml libraries in the using section.
First we create a connection object to connect to the database then a command object to pass sql to the server through the connection. A data reader reads the data into the Grid.
In the button we create a new command that selects the XML file for the selected memo and attaches it to the XML Control. We also call the XSLT file we had made.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; //add these three libraries
using System.Data.SqlClient;
using System.Xml;
public partial class _Default : System.Web.UI.Page
{
SqlConnection connect;
protected void Page_Load(object sender, EventArgs e)
{
connect = new SqlConnection("Data Source=localhost;initial catalog=Automart;user=EmployeeLogin;password=pass");
string sql = "Select AutomartMemoID, MemoDescription from AutomartMemos";
SqlCommand cmd = new SqlCommand(sql, connect);
SqlDataReader reader = null;
connect.Open();
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Dispose();
connect.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xDoc = new XmlDocument();
string sql = "Select memo from AutomartMemos where AutomartMemoID=@ID";
SqlCommand cmd = new SqlCommand(sql, connect);
cmd.Parameters.AddWithValue("@ID", int.Parse(GridView1.SelectedRow.Cells[1].Text));
XmlReader xreader = null;
connect.Open();
xreader = cmd.ExecuteXmlReader();
xDoc.Load(xreader);
xreader.Close();
connect.Close();
Xml1.Document = xDoc;
Xml1.TransformSource = MapPath("memo.xslt");
}
}
Here is the code for the XSLT:
memo.xslt
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
xmlns="http://www.w3.org/1999/xhtml" xmlns:m ="http://www.spconger.com/memo" >
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<h2>Automart Memo</h2>
<hr/>
<p>
<strong>To: </strong>
<xsl:value-of select="m:memo/m:header/m:to"/>
</p>
<p>
<strong>From: </strong>
<xsl:value-of select="m:memo/m:header/m:from"/>
</p>
<p>
<strong>Date: </strong>
<xsl:value-of select="m:memo/m:header/m:date"/>
</p>
<p>
<strong>About: </strong>
<xsl:value-of select="m:memo/m:header/m:about"/>
</p>
<hr/>
<xsl:for-each select="//m:memo/m:body/m:p">
<p>
<xsl:value-of select="."/>
</p>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
We started a new empty Web Site in visual Studio. We added a new web form and then added an existing item--the XSLT document. Here is the code for the Web Form. We added a GridView, a button and an XML control. For the Gridview we also added a new column which was a button, (type link, command Select, text Select) Most of the other markup for the web grid is just formatting and could be left out.
Default.Aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4">
<Columns>
<asp:ButtonField CommandName="Select" Text="Select" />
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Get memo"
onclick="Button1_Click" />
<asp:Xml ID="Xml1" runat="server"></asp:Xml>
</div>
</form>
</body>
</html>
In the code behind we used basic ADO. We needed to Add the System.Data, System.Data.SqlClient and the System.Xml libraries in the using section.
First we create a connection object to connect to the database then a command object to pass sql to the server through the connection. A data reader reads the data into the Grid.
In the button we create a new command that selects the XML file for the selected memo and attaches it to the XML Control. We also call the XSLT file we had made.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; //add these three libraries
using System.Data.SqlClient;
using System.Xml;
public partial class _Default : System.Web.UI.Page
{
SqlConnection connect;
protected void Page_Load(object sender, EventArgs e)
{
connect = new SqlConnection("Data Source=localhost;initial catalog=Automart;user=EmployeeLogin;password=pass");
string sql = "Select AutomartMemoID, MemoDescription from AutomartMemos";
SqlCommand cmd = new SqlCommand(sql, connect);
SqlDataReader reader = null;
connect.Open();
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Dispose();
connect.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xDoc = new XmlDocument();
string sql = "Select memo from AutomartMemos where AutomartMemoID=@ID";
SqlCommand cmd = new SqlCommand(sql, connect);
cmd.Parameters.AddWithValue("@ID", int.Parse(GridView1.SelectedRow.Cells[1].Text));
XmlReader xreader = null;
connect.Open();
xreader = cmd.ExecuteXmlReader();
xDoc.Load(xreader);
xreader.Close();
connect.Close();
Xml1.Document = xDoc;
Xml1.TransformSource = MapPath("memo.xslt");
}
}
Wednesday, July 20, 2011
Function Overloading
A function can be "overloaded" by changing its signature, that is by changing the types or numbers of parameters. It is the data type that matters not the variable name. Additionally the order of the parameters does not count. So (double, int) is the same as (int, double) as far as the compiler is concerned.
We also used separated the function prototypes from the function bodies again using header files.
Here is the header file:
Payrollheader.h
double GetPay(double rate, int hours);
double GetPay(double salary);
double GetPay(double contractAmt, double percent);
Here is the function definition file
PayrollFunctions.cpp
double GetPay(double rate, int hours)
{
double pay=0;
if (hours >40)
{
pay=rate * (hours+((hours-40) * 1.5));
}
else
{
pay=rate*hours;
}
return pay;
}
double GetPay(double salary)
{
return salary / 52;
}
double GetPay(double contractAmt, double percent)
{
return contractAmt * percent;
}
And here is the program file which calls each overloaded version of the GetPay() function:
Program.cpp
#include <iostream>
#include "PayrollHeader.h"
using namespace std;
int main()
{
cout << "how many hours did you work? "<< endl;
int hours;
cin >> hours;
cout << "What was your hourly rate?"<<endl;
double rate;
cin >> rate;
cout << "Your weekly pay is " << GetPay(rate,hours) << endl;
cout << "*************************************" <<endl;
cout << "What is your annual salary?" << endl;
double sal;
cin >> sal;
cout << "Your weekly pay is " << GetPay(sal) <<endl;
cout << "*************************************" <<endl;
cout << "What is your total contract amount?" << endl;
double cAmt;
cin >>cAmt;
cout << "What percent is this week of your contract? " << endl;
double prct;
cin >> prct;
double pay=GetPay(cAmt,prct);
cout << "Your weekly pay is " << pay << endl;
char c;
cin >> c;
}
We also used separated the function prototypes from the function bodies again using header files.
Here is the header file:
Payrollheader.h
double GetPay(double rate, int hours);
double GetPay(double salary);
double GetPay(double contractAmt, double percent);
Here is the function definition file
PayrollFunctions.cpp
double GetPay(double rate, int hours)
{
double pay=0;
if (hours >40)
{
pay=rate * (hours+((hours-40) * 1.5));
}
else
{
pay=rate*hours;
}
return pay;
}
double GetPay(double salary)
{
return salary / 52;
}
double GetPay(double contractAmt, double percent)
{
return contractAmt * percent;
}
And here is the program file which calls each overloaded version of the GetPay() function:
Program.cpp
#include <iostream>
#include "PayrollHeader.h"
using namespace std;
int main()
{
cout << "how many hours did you work? "<< endl;
int hours;
cin >> hours;
cout << "What was your hourly rate?"<<endl;
double rate;
cin >> rate;
cout << "Your weekly pay is " << GetPay(rate,hours) << endl;
cout << "*************************************" <<endl;
cout << "What is your annual salary?" << endl;
double sal;
cin >> sal;
cout << "Your weekly pay is " << GetPay(sal) <<endl;
cout << "*************************************" <<endl;
cout << "What is your total contract amount?" << endl;
double cAmt;
cin >>cAmt;
cout << "What percent is this week of your contract? " << endl;
double prct;
cin >> prct;
double pay=GetPay(cAmt,prct);
cout << "Your weekly pay is " << pay << endl;
char c;
cin >> c;
}
Tuesday, July 19, 2011
Presentation links
Here are links to today's presentation and the presentations last Thursday:
Snapshot Presentation
Partition Presentation
Retrieving and Manipulating data
Snapshot Presentation
Partition Presentation
Retrieving and Manipulating data
XML schema and XML in SQL Server
Remember we made the xml file for the memos in Visual Studio and then used the xml menu build schema option to create the schema.
Here is the Xml Schema collection
Create xml schema collection automartmemos
as
'<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.spconger.com/memo" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="memo">
<xs:complexType>
<xs:sequence>
<xs:element name="header">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string" />
<xs:element name="from" type="xs:string" />
<xs:element name="about" type="xs:string" />
<xs:element name="date" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="body">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="p" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>'
Now we create a table that has a field that uses the xml data type. We bind that field to the xml schema collection that we have just created.
Create table AutomartMemos
(
AutomartMemoID int identity(1,1) primary key,
MemoDescription nvarchar(255),
Memo xml (dbo.automartmemos)
)
Now we insert into the database. The xml below will fail because the from and about elements are in reverse order. When it matches the structure of the xml document against the schema it will see the difference and throw an error.
Insert into AutomartMemos(MemoDescription, Memo)
Values('Too much of nothing',
'<?xml version="1.0" encoding="utf-8"?>
<memo xmlns="http://www.spconger.com/memo">
<header>
<to>everyone</to>
<about>nothing</about>
<from>me</from>
<date>7/19/2011</date>
</header>
<body>
<p>There is nothing going on today</p>
<p>But we have to appear busy</p>
</body>
</memo>')
Below is an example of xml raw with all the possible options. It is set to provide a root element named persons and a grouping element named person. After the SQL I show a small part of the output.
Select * From Person
for xml raw('person'), root('persons'),elements
<persons>
<person>
<Personkey>1</Personkey>
<LastName>Anderson</LastName>
<FirstName>Jay</FirstName>
</person>
<person>
<Personkey>2</Personkey>
<LastName>Zimmerman</LastName>
<FirstName>Toby</FirstName>
</person>
<person>
<Personkey>3</Personkey>
<LastName>Mann</LastName>
<FirstName>Louis</FirstName>
</person>
. . .
Here is an example of xml auto. It allows for deeper and more complex
hierarchies of xml. I am showing a fragment of the output.
Select LastName, firstname, LicenseNumber, VehicleMake, VehicleYear
From Person
inner join customer.vehicle
on Person.Personkey=Customer.Vehicle.PersonKey
order by Lastname
for xml auto, root('vehicles'), elements
<Person>
<LastName>Fabre</LastName>
<firstname>Jill</firstname>
<customer.vehicle>
<LicenseNumber>LKJ098</LicenseNumber>
<VehicleMake>Ford Freestar</VehicleMake>
<VehicleYear>2004</VehicleYear>
</customer.vehicle>
<customer.vehicle>
<LicenseNumber>OPO234</LicenseNumber>
<VehicleMake>Jeep Cherokee</VehicleMake>
<VehicleYear>1998</VehicleYear>
</customer.vehicle>
</Person>
Here is the Xml Schema collection
Create xml schema collection automartmemos
as
'<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.spconger.com/memo" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="memo">
<xs:complexType>
<xs:sequence>
<xs:element name="header">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string" />
<xs:element name="from" type="xs:string" />
<xs:element name="about" type="xs:string" />
<xs:element name="date" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="body">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="p" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>'
Now we create a table that has a field that uses the xml data type. We bind that field to the xml schema collection that we have just created.
Create table AutomartMemos
(
AutomartMemoID int identity(1,1) primary key,
MemoDescription nvarchar(255),
Memo xml (dbo.automartmemos)
)
Now we insert into the database. The xml below will fail because the from and about elements are in reverse order. When it matches the structure of the xml document against the schema it will see the difference and throw an error.
Insert into AutomartMemos(MemoDescription, Memo)
Values('Too much of nothing',
'<?xml version="1.0" encoding="utf-8"?>
<memo xmlns="http://www.spconger.com/memo">
<header>
<to>everyone</to>
<about>nothing</about>
<from>me</from>
<date>7/19/2011</date>
</header>
<body>
<p>There is nothing going on today</p>
<p>But we have to appear busy</p>
</body>
</memo>')
Below is an example of xml raw with all the possible options. It is set to provide a root element named persons and a grouping element named person. After the SQL I show a small part of the output.
Select * From Person
for xml raw('person'), root('persons'),elements
<persons>
<person>
<Personkey>1</Personkey>
<LastName>Anderson</LastName>
<FirstName>Jay</FirstName>
</person>
<person>
<Personkey>2</Personkey>
<LastName>Zimmerman</LastName>
<FirstName>Toby</FirstName>
</person>
<person>
<Personkey>3</Personkey>
<LastName>Mann</LastName>
<FirstName>Louis</FirstName>
</person>
. . .
Here is an example of xml auto. It allows for deeper and more complex
hierarchies of xml. I am showing a fragment of the output.
Select LastName, firstname, LicenseNumber, VehicleMake, VehicleYear
From Person
inner join customer.vehicle
on Person.Personkey=Customer.Vehicle.PersonKey
order by Lastname
for xml auto, root('vehicles'), elements
<Person>
<LastName>Fabre</LastName>
<firstname>Jill</firstname>
<customer.vehicle>
<LicenseNumber>LKJ098</LicenseNumber>
<VehicleMake>Ford Freestar</VehicleMake>
<VehicleYear>2004</VehicleYear>
</customer.vehicle>
<customer.vehicle>
<LicenseNumber>OPO234</LicenseNumber>
<VehicleMake>Jeep Cherokee</VehicleMake>
<VehicleYear>1998</VehicleYear>
</customer.vehicle>
</Person>
Monday, July 18, 2011
Functions Arrays and Header files
For these examples we pass Arrays as pointers to arrays. I also separate the function prototypes, the actual function definitions and the main into three files. The prototypes are put in a header file. the actual definitions are stored in a .cpp file, as is the main() function.
Both the function definitions and the main must have an include statement that includes the header file.
Here is the main file.
#include <iostream>
#include "ArrayFunction.h"
using namespace std;
int main()
{
CreateArray();
char c;
cin >> c;
}
Notice how simple and clean it is. It only calls the starting function. Here is the
header file:
ArrayFunction.h
void CreateArray();
void FillArray(int * arr, int size);
void DisplayArray(const int * arr, int size);
int SumArray(const int * arr, int size);
A couple of notes on the function prototypes. Notice we are passing pointers to an array called "arr." Whenever you pass an array as an argument you are in fact passing an pointer. This format just makes it explicit.
Also note the use the "const" keyword. It protects the array from being changed by the function it is passed to. I didn't do it for the FillArray() function because it needs to change the array.
Here is the file that has the actual function definitions:
FunctionArrays.cpp
#include <iostream>
#include "ArrayFunction.h"
#include <cmath>
#include <ctime>
using namespace std;
void CreateArray()
{
int arr[10];
FillArray(arr,10);
}
void FillArray(int * arr, int size)
{
srand(time(0));
for(int i=0;i<size;i++)
{
int number = rand();
arr[i]=number;
}
DisplayArray(arr, size);
}
int SumArray(const int * arr, int size)
{
int total=0;
for(int i=0;i<size;i++)
{
total += arr[i];
}
return total;
}
void DisplayArray(const int *arr, int size)
{
for (int i=0;i<size;i++)
{
cout << arr[i]<<endl;
}
cout << "\n\nthe total is: "<< SumArray(arr, size) << endl;
}
This kind of separation of prototype from definition adds to clarity and re-usability of the code. We will see more of this when we do classes.
Both the function definitions and the main must have an include statement that includes the header file.
Here is the main file.
#include <iostream>
#include "ArrayFunction.h"
using namespace std;
int main()
{
CreateArray();
char c;
cin >> c;
}
Notice how simple and clean it is. It only calls the starting function. Here is the
header file:
ArrayFunction.h
void CreateArray();
void FillArray(int * arr, int size);
void DisplayArray(const int * arr, int size);
int SumArray(const int * arr, int size);
A couple of notes on the function prototypes. Notice we are passing pointers to an array called "arr." Whenever you pass an array as an argument you are in fact passing an pointer. This format just makes it explicit.
Also note the use the "const" keyword. It protects the array from being changed by the function it is passed to. I didn't do it for the FillArray() function because it needs to change the array.
Here is the file that has the actual function definitions:
FunctionArrays.cpp
#include <iostream>
#include "ArrayFunction.h"
#include <cmath>
#include <ctime>
using namespace std;
void CreateArray()
{
int arr[10];
FillArray(arr,10);
}
void FillArray(int * arr, int size)
{
srand(time(0));
for(int i=0;i<size;i++)
{
int number = rand();
arr[i]=number;
}
DisplayArray(arr, size);
}
int SumArray(const int * arr, int size)
{
int total=0;
for(int i=0;i<size;i++)
{
total += arr[i];
}
return total;
}
void DisplayArray(const int *arr, int size)
{
for (int i=0;i<size;i++)
{
cout << arr[i]<<endl;
}
cout << "\n\nthe total is: "<< SumArray(arr, size) << endl;
}
This kind of separation of prototype from definition adds to clarity and re-usability of the code. We will see more of this when we do classes.
Subscribe to:
Posts (Atom)