Monday, 4 March 2013

Activity 9: Post-test loop to display Fibonacci numbers


Activity 9: Post-test loop to display Fibonacci numbers
Create a program to generate the first 20 Fibonacci numbers. Use a counter to control the
number of iterations in a post-test loop.
·  Start a new single-document project called Numbers. Open NumbersDoc.h (from the
header files) and add three CString objects (data, data1 and data2) in the public section.
·  Open NumbersDoc.cpp and initialise the objects.
CNumbersDoc::CNumbersDoc()
{
// TODO: add one-time construction code here
data = "The first 20 Fibonacci numbers are:";
data1 = "";
data2 = "";
}
·  Open NumbersView.cpp and add the code to display the Fibonacci numbers in the
OnDraw() method.
void CNumbersView::OnDraw(CDC* pDC)
{
CNumbersDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
short x = 0;
short y = 1;
int counter = 1;
CString new1 = "";
CString new2 ="";
do
{
//Declare variables to
//format the values as
//text.
//Use post-test loop
new1.Format("%ld", x);
new2.Format("%ld", y);
pDoc->data1 += new1;
pDoc->data1 += " ";
pDoc->data1 += new2;
pDoc->data1 += " ";
x+=y;
y+=x;
counter +=2;
//Format values of x, y
//Concatenate to string
//Add 3 spaces
//Change value of x,y
//Changes loop
}
while (counter < 10);
do
{
//condition to
//terminate loop.
//This post-test loop
//concatenates values
new1.Format("%ld", x);
new2.Format("%ld", y);
pDoc->data2 += new1;
pDoc->data2 += " ";
pDoc->data2 += new2;
pDoc->data2 += " ";
x+=y;
y+=x;
counter +=2;

}
while ((counter < 20) && (counter >= 10));
pDC->TextOut(0, 0, pDoc->data);
pDC->TextOut(0, 20, pDoc->data1);
pDC->TextOut(0, 40, pDoc->data2);
//Displays strings on
//screen – each string
//on a new line.
}
·  Build and run.

No comments:

Post a Comment