Hello
My program takes in a number & uses a recursive function to display that number backwards. eg input = 473, output= 374.
I have to submit the program for marking, but they always throw in some curve ball test to make sure that your program will work for all cases.
Can you take a look at my program and tell me if it will work for all numbers? Or can you see an exception when this algorithm wont work?
Our tutor actually gave us the answer :P but mine is different & I am trying to be sure my code works for all numbers/cases so I dont loose a mark again :P
// My way of doing it
void reverseDigits(int x)
// displays the int x with its digits in reverse order.
// recursive algorithm
{
if (x>1) { // will this work for all numbers??
cout << x%10;
reverseDigits(x/10);
}
}
// My tutors example
void reverseDigits2(int x) {
cout << x%10;
if (x>10) {
reverseDigits2(x/10);
}
}
whole program:
#include <iostream>
using namespace std;
void reverseDigits(int x);
void reverseDigits2(int x);
int main()
{
int number;
cout << "Enter a number : " << flush;
if (cin >> number)
{
cout << number << " reversed is ";
reverseDigits(number);
cout << endl;
}
else
cout << "Invalid input " << flush;
system("pause");
return 0;
}
// My way of doing it
void reverseDigits(int x)
// displays the int x with its digits in reverse order.
// recursive algorithm
{
if (x>1) { // will this work for all numbers??
cout << x%10;
reverseDigits(x/10);
}
}
// My tutors example
void reverseDigits2(int x) {
cout << x%10;
if (x>10) {
reverseDigits2(x/10);
}
}