The function accepts a number n
and displays it recursively with commas.
As well as a general code review, I'm interested in suggestions for alternatives to counting to tell when to print the commas. I tried if(mod%10000 == 0)
; that works on the first 3 numbers, but after that mod
is always a multiple of 10000
.
#include <iostream>
using namespace std;
void RecursiveCommas(long long n, int mod = 10, int i = 0);
int main()
{
RecursiveCommas(123456789);
return 0;
}
void RecursiveCommas(long long n, int mod, int i){
if(n%mod==n){ //base case
if(i%3 == 0 && i != 0)
cout << (n%mod) / (mod/10) << ",";
else
cout << (n%mod) / (mod/10);
}
else{
if(i%3 == 0 && i != 0){ //add commas
RecursiveCommas(n, mod*10, i+1);
cout << (n%mod) / (mod/10) << ",";
}
else { //no comma needed
RecursiveCommas(n, mod*10, i+1);
cout << (n%mod) / (mod/10);
}
}
}