View Single Post
Old Aug 24th, 2005, 1:26 AM   #6
stevengs
Professional Programmer
 
stevengs's Avatar
 
Join Date: May 2005
Location: Bad Nauheim, Germany
Posts: 436
Rep Power: 4 stevengs is on a distinguished road
Quote:
Originally Posted by melee28
stevengs- I wasn't directed to do anything really, this is for my own self education, not for school or anything. Recursion hasn't been discussed in the text yet and while I'm not opposed to using recursion or iteration, I guess I don't understand why it's necessary in this case. I know it's easier to use recursion or loops, it's just not the point of my "mental exercise". If my (limited) understanding is correct, nearly everything that can be done with a loop can also be done without one (though in a more complicated manner.) I know it's masochistic of me, but I want to see if it can be done and how.

melee28
By "directed", I meant directed by the book's author. They usually explain what approach they want you to use. If you do not use iteration or recursion, any program you write will essentially be a series of print statements that is only able to show a finite set of numbers. So in your program:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
   int fib1 = 0;     // This is the initialization
   int fib2 = 1;     //  phase, where you initalize the 
   int fib3 = 1;     //  variables.  This must only be 
   int temp = 0;     //  performed once in this program.
 
   printf("%2d", fib1);
   printf("%2d", fib2);
   printf("%2d", fib3);
 
   //****************************************
   //  The following must be performed over and over until
   //   you reach the fibonacci number you're targeting.

   temp = fib1 + fib2;
   fib1 = fib2;
   fib2 = fib3;
   fib3 = temp;  
  
 
   printf("%2d", fib3);  
  
  
   printf("\n");
	
   //*****************************************

   system("PAUSE");
   return 0;
}

Basically you must copy and paste the section marked 6 times.

 
...
   temp = fib1 + fib2;
   fib1 = fib2;
   fib2 = fib3;
   fib3 = temp;  
   printf("%2d", fib3);  
   printf("\n");
//*****************
   temp = fib1 + fib2;
   fib1 = fib2;
   fib2 = fib3;
   fib3 = temp;  
   printf("%2d", fib3);  
   printf("\n");
//*****************
   temp = fib1 + fib2;
   fib1 = fib2;
   fib2 = fib3;
   fib3 = temp;  
   printf("%2d", fib3);  
   printf("\n");
//*****************

...

It is basically always the same... Wetten( initialize ), Lather and Rinse( excecute ), Repeat as necessary! The trick is usually in deciding when 'necessary' no longer applies.

Apparently, the author wishes you to ask yourself, "There must be a more intelligent way to perform this repetitive and mundane task?", before "SHAZAM!"-ing you with loops or recursion.
__________________
-Steven
"Is this a piece of your brain?" - Basil Fawlty

Last edited by stevengs; Aug 24th, 2005 at 1:42 AM.
stevengs is offline   Reply With Quote