sum of last and first digit of a number using recursion function

May 14, 2020 at 9:21am
HEllo. i wrote those functions which look like recursive functions but i'm not satisfied i feel like it's not recursive, is there a way to write only one recursive function to do both jobs? or two functions but in a "real" recursive way ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

int first(int num)
{
   if (num<10)
   return num;
   else
   while (num>10)
   return first(num/10);
}
int last(int num)
{
    if(num<10)
    return num;
    else
    return last(num%10);
}

int main()
{
 int x;
 cin>>x;
 cout<<"sum is "<<first(x)+last(x)<<endl;
}
May 14, 2020 at 10:04am
In int first() you can simply remove lines 8 and 9.


You second function could be simplified to
1
2
3
4
int last(int num)
{
   return num%10;
}

but it's barely worth a function at all.
May 14, 2020 at 2:13pm
Your original program did not work if you put in numbers greater than 100.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

int first(int num)
{
   if (num<10)
   return num;
  
   first(num/10);
}


int main()
{
    
 int x;
 cin>>x;
 
 if(x>10) {
 cout<<"sum is "<< first(x) + x%10<<endl;
 }
 
else {
     cout<<"sum is "<< x <<endl;
}


return 0;
}
Last edited on May 14, 2020 at 2:14pm
May 14, 2020 at 10:31pm
thank you first of all.
actually it worked for me with those two functions with any number i even entered 10 digits and it worked but i wanted a simple recursive function to do the job, my functions were more like a normal function.
May 15, 2020 at 4:04am
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int sum_first_and_last(unsigned long n, int top = 1)
{
    return n < 10 ? n : sum_first_and_last(n / 10, 0) + n % 10 * top;
}

int main()
{
    std::cout << sum_first_and_last(31234567890123456) << '\n';
}

Topic archived. No new replies allowed.