Sunday, September 23, 2012
Recursive Function
#include <iostream>
#include "Node.h";
using namespace std;
//factorial number
int factoria(int num){
//initial value
if (num == 0){
return 1;
} else {
return num * factoria(num-1);
}
}
//find the largest in a array
int FindLargest(int* listArray, int lowerIndex, int upperIndex){
//base class
if(lowerIndex == upperIndex){
return listArray[lowerIndex];
}
//recursive call
int currMax = FindLargest(listArray, lowerIndex+1, upperIndex);
if(currMax > listArray[lowerIndex]){
return currMax;
} else {
return listArray[lowerIndex];
}
}
void printRevertLinkedList(Node* node){
//base case
if(node->next == NULL){
cout << node->value << ",";
return;
}
printRevertLinkedList(node->next);
cout << node->value << ",";
}
void printRevertedLinkedListSimp(Node* node){
if(node != NULL){
printRevertLinkedList(node->next);
cout << node->value << ",";
}
}
int Fabonacci(int number){
//validate the input parameters
if(number <= 0){
cout << "invalid input." << endl;
return 0;
}
//base class
if (number == 1 || number == 2){
return 1;
}
return Fabonacci(number-1)+Fabonacci(number-2);
}
//tower of hanoi
void moveTower(int count, int node1, int node2, int node3){
if (count <= 0){
//cout << "the end of round from " << node1 << " to " << node2 << endl;
return;
}
moveTower(count-1, node1, node3, node2);
cout << "move the single one from " << node1 << " to " << node2 << endl;
moveTower(count-1, node3, node2, node1);
}
//change from decimal to binary -- positive integer
void decimalToBinary(int number, int base){
//validate input parameter
if (number < 0){
cout << "Negative input is invalid. " << endl;
}
//base case
if (number == 0){
return;
}
decimalToBinary(number/base, base);
cout << number%base;
}
Subscribe to:
Comments (Atom)