Hi there, I'm am trying to write a recursive C++ function that writes the digits of a positive decimal integer in reverse order.

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <math.h>
#include <string>
using std::string;
using namespace std;


int reverse_num (int number, int m) ;
int main()
{
	int number;
	int m=0;
	cout << "Enter number to reverse :";
	cin >> number;
	cout << reverse_num(number,0) << endl; //calling the function
	system("pause") ;
	return 0;
}
int reverse_num(int number,int m)
{
	if(number==0)
		return m; //base (exit condition)
	m*=10;
	m+=number%10;
	return reverse_num(number/10,m); //recursive function called here
}

I'm compiling the code in Visual C++, so far the code can only reverse integers and I haven't a notion on how to keep the numbers after the decimal point. I'm not even sure if the number after the decimal point should exist! Should, for example, 27.3 become 72 or 372? Any advice would be much appreciated!

positive decimal integer

as far as i know...integers dont have decimal values...

if u want to use decimals, dont use int... use float or double... whichever caters ur needs better

27.3 become 72 or 372?

and this ....? 27.3 in reverse should actually become 3.72.

what is your desired output?

you are asking sensible questions about how you would reverse the digits of a number.

And the reason why you are having problems is that it is not defined
behaviour - so to code it for non-integers requires a decision as to what is intended.

Option one treat it as a formatting exercise

read in the number as a std::string
identify any digits or decimal point:
ie

std::string num;
std::cout << "input number:" << std::endl;
std::cin >> num;
std::string digits("0123456789.");
std::string::size_type start = num.find_first_of(digits, 0);
std::string before_digits = num.substr(0, start);
std::string end = num.find_first_not_of(digits, start);
std::string after_digits = num.substr(end);
std::string to_reverse = num.substr(start, end - start);

std::string rev_num = before_digits + reverse(to_reverse) + after_digits;

now this code will reverse the digits by the use of [icode]reverse[/icode]

the idea is that
27.3
becomes
3.72
so you reverse the point as well

now if you need a number because of an assignment you can convert the string back to a float before you reverse

recursion is still tricky for the number as it really isn't a recursive task if you use decimals but you could find the decimal in a string
convert a string to an int
so say

"34.567"
find point p = 2 & num_digits = 5
conver to float->
34.567
remove point
*1000
34567
reverse recursively while > 0
76543
reintroduce "."
765.43

the other possible implementation
is reverse before and after the decimal point so

you change
3567.245
to
7653.542

where

you split you double into an int and the decimal has to then be converted to an int by *10^n

n can be found with logs

but with recursion how do you know how to stop without knowing how many steps with a decimal??

so this is more iteration

but the first makes more sense to me.
What I would recommend is that your reverse function if called twice gives you the same answer.

I hope this has helped

and this ....? 27.3 in reverse should actually become 3.72.

what is your desired output?

I believe your right in saying that the reverse for 27.3 should become 3.72.


now if you need a number because of an assignment you can convert the string back to a float before you reverse

recursion is still tricky for the number as it really isn't a recursive task if you use decimals but you could find the decimal in a string
convert a string to an int
so say
"34.567"
find point p = 2 & num_digits = 5
conver to float->
34.567
remove point
*1000
34567
reverse recursively while > 0
76543
reintroduce "."
765.43

This is the implementation method I'm looking for - I'm just not sure on how to convert to float and how to remove the point and reintroduce it again.

This is a fairly easy task if you restrict yourself to strings

//assuming number has nothing but "0123456789."
//it could have '-' but clean to just the digits
std::string number("31.2445");
//converting size_type to int
int sz =  (int) number.size();
int point = -1; 

//put the num into an int ignoring the point
int num(0);
for(int j = 0; j < sz; ++j)
{
 char current_letter = number[j];
  if(is_digit(current_letter) == true)
  {
     num * = 10;
      num += from_digit(current_letter);
  }
 else if(current_letter == '.')
  {
     if(point != -1)
     {
        std::cout << "second point found at: " << j << std::endl;
        break;
      }
      else
      {
        point = j;
      }
   }
}

//now num is 312445
//point is 2 and sz is 7

//reverse the number using a function
int r_num  = reverse(num);

//r_num should be 544213

//need to convert the point into a divider
double div(1.0);
for(int np(0); np < p; ++np)
{
  div * 10.0;
}

double d_r_num = r_num / div;

now this code is a little confusing and it converts an int
back to a decimal using a divider.

you have to still write

bool is_digit(char c);
int from_digit(char c);

in ascii the numbers go from '0' hint int i = '1' - '0'; i would be 1

This is the implementation method I'm looking for - I'm just not sure on how to convert to float and how to remove the point and reintroduce it again.

This is a fairly easy task if you restrict yourself to strings

//assuming number has nothing but "0123456789."
//it could have '-' but clean to just the digits
std::string number("31.2445");
//converting size_type to int
int sz =  (int) number.size();
int point = -1; 

//put the num into an int ignoring the point
int num(0);
for(int j = 0; j < sz; ++j)
{
 char current_letter = number[j];
  if(is_digit(current_letter) == true)
  {
     num * = 10;
      num += from_digit(current_letter);
  }
 else if(current_letter == '.')
  {
     if(point != -1)
     {
        std::cout << "second point found at: " << j << std::endl;
        break;
      }
      else
      {
        point = j;
      }
   }
}

//now num is 312445
//point is 2 and sz is 7

//reverse the number using a function
int r_num  = reverse(num);

//r_num should be 544213

//need to convert the point into a divider
double div(1.0);
for(int np(0); np < p; ++np)
{
  div * 10.0;
}

double d_r_num = r_num / div;

now this code is a little confusing and it converts an int
back to a decimal using a divider.

you have to still write

bool is_digit(char c);
int from_digit(char c);

in ascii the numbers go from '0' hint int i = '1' - '0'; i would be 1

Thanks for the detailed answer, but I can't even begin to comprehend it lol

You have an input of a number as a string because a float could have an unknown number of decimals

you want to convert that number to something that is a number within the computer so lets take the simple int example

std::string num("57657");

std::string::size_type sz = num;
//therefore sz = 5 as 
//57657 is 5 chars long

//num[0] = 5;
//num[1] = 7;
//num[2] = 6;
//num[3] = 5;
//num[4] = 7;

int val(0);
for(int i = 0; i < sz; ++i)
{
 //check that input is as expected
char c = num[i];
 if(c >= '0' && c <='9')
 {
    //have a digit to add
    //val +=  int(c - '0'); //new digit ie 5
    //but now know that we have another digit therefore
    // number is 10 times as big as
    val *= 10;
    val += int(c - '0');
  }
  else
  {
     //not a digit
  }
}
//so val should be 57675

the next step is to put the decimal point back in at the end

in real life you would just reverse the string but it would not
use your existing code and it is an assignment

if this is still confusing you could read up about std::string

Thanks for the detailed answer, but I can't even begin to comprehend it lol

as far as i see...this should been done recursively as the OP said...

int reverse_num(int number,int m)
{
if(number==0)
return m; //base (exit condition)

m*=10;
m+=number%10;
return reverse_num(number/10,m); //recursive function called here
}

if this does help any... ive coded the problem in c#...


so all u have to do is convert this code to c++ ...which shouldnt be to hard..

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			string num = Console.ReadLine();
			reverse(num, num.Length - 1);
			Console.ReadLine();

		}
		
		static string reverse(string num, int index)
		{
			if (num == null)
					return null;

			if (index > -1)
			{
				Console.Write(num[index]);
				return reverse(num, index - 1);
			}
			return null;
		}
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.