Dear Cprogramming.com administrators and members,
Hello everyone, a pleasant day to you all. I hope that everyone's doing great upon reading this forum. Well, I'm sort of experimenting with recursive functions and I feel great when I learned how to program them especially when using it on factorials, fibonacci sequence, etc. I have this sample program, here's the simple code:
Code:#include <iostream> class Counting { public: int count (int x, int y) { //this is a countdown int ctr=0; if (x==y) return 1; else { ctr = y+count (x-1,y); return ctr; } }//end of count() }; int main() { int in, ctr, choice; Counting countmain; std::cout << "Please select from the menu: " << std::endl << std::endl; std::cout << "[1] count up " << std::endl; std::cout << "[2] count down " << std::endl; std::cout << "\nPlease enter your choice: "; std::cin>> choice; if (choice==1){ std::cout<<" count from 1 up to "; std::cin>> in; for(ctr=1; ctr<=in; ctr++) std::cout << countmain.count(in,1) << std::endl; } return 0; }
Well, this program will allow user to choose whether he/she wants to count up or count down so to speak. If the user choose 1, then the program will count from 1 up to n, where n is the number he/she input. For example I choose 1 then enter 10, so that means the program will count from 1 to 10, but unfortunately, the recursive function printed number 10, but ten times, not 1, 2, 3,...10 as I want. I just want to ask everyone's help on what changes should I made to my code make the member function count() to count down numbers. I know this can be relatively easy using loops, but somehow I'm just trying it on recursive functions. I hope someone could help me on this one.
Thank you in advance and God bless everyone.
Respectfully yours,
MarkSquall