I am writing a program to recursively insert commas into an int larger than 1000. I have began writing the program but am having trouble. Here is what I have so far.
#include <iostream>
#include <iomanip>
usingnamespace std;
void commas();
int main(void)
{
int number;
int i, n;
int num[n];
int number1;
cout<<"Enter a positive integer without commas:"<<endl;
cin>>number;
int commas();
return 0;
}
void commas()
/* -----------------------------------------------------
Precondition: None.
Postcondition: comma inserted in number
-------------------------------------------------------*/
{
int counter, n;
int num[n];
int number1;
int number;
n=1;
while(number>0)
{
int numb();
num[n]=number1;
number=number-(number1*(10)^counter);
n++;
cout<<"In function commas"<<endl;
cout<<"Number now is: "<<number<<endl;
}
n=1;
while(n<4)
{
cout<<""<<num[n]<<"";
n++;
}
while(n>=4)
{
cout<<"','";
cout<<""<<num[n-2]<<"";
cout<<""<<num[n-1]<<"";
cout<<""<<num[n]<<"";
n=n-3;
}
return;
}
void numb()
{
int number, number1;
int counter;
number1=number;
cout<<"Entering function numb"<<endl;
cout<<"Number is: "<<number<<endl;
counter=0;
while(number1>10)
{
number1=number1/10;
counter++;
}
return;
}
I believe things would be much easier if you handled your number as a string.
Also, if you are careful, your recursive solution can be as fast as an iterative one.
EDIT: Damn... g++ doesn't seem to be able to optimize this... Or am I doing something wrong?
EDIT2: Mmm... Looks like the tail call optimization can only be done with primitive types...
EDIT3: You can do it in Scala.