Recursion

himlastar

Member
Joined
Mar 16, 2019
Messages
10
Programming Experience
Beginner
Hello, I'm new to this forum, and im new as a Progammer,
I am studying at university, and there's a task I have given
To make a Recursion.

I need to input a number like - 123456
and it adds every number seperate, and like 1+2+3+4+5+6 = 21
And I have no Idea how do I seperate numbers if its together as one?

514

This is what I need to make.
And I have given a example from Recursion factorial - this code.
class Rekursija
{
static void Main(string[] args)
{ i= int.Parse(Console.ReadLine());
printText(i);
}
static void printText(int i)
{
Console.WriteLine(i); if (i > 0) { i--; printText(i);
} } }
 
Write a method that has a string of digits as an input and returns the sum of those digits. Inside the method, break the string into two parts: the first character and the rest. First, convert the first substring to a number. You can then call the same method again, i.e. make a recursive call, and pass the second substring as an argument. Finally, add the result of the recursive call to the first number and return the result. If you call f("123456") then that will be 1 + f("23456") and the latter will be 2 + f("3456") and so on.
 
Back
Top Bottom