I need help with recursive sum | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I need help with recursive sum

I don't know how to do it, I tried it but I get an error. This is the description of the problem: Write a program that takes N numbers as input and recursively calculates the sum of all numbers from 1 to N. Input example 5 Output example fifteen Explanation 5 + 4 + 3 + 2 + 1 = 15. This is code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { int number = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(Sum(number)); } static int Sum(int num) { //completa el método recursivo } } }

26th Jun 2021, 2:59 AM
Alex Narváez
Alex Narváez - avatar
5 Answers
+ 2
recursive function must call itself until a base case... if you give N as argument, you must return N+Sum(N-1) until N reach 0... so: if (num == 0) { return 0; } return num + Sum(num - 1);
26th Jun 2021, 3:13 AM
visph
visph - avatar
+ 1
Okay, now I understand it better. I really appreciate your help, it helped me a lot, I understood it better and I learned something new. Thank you visph
26th Jun 2021, 3:18 AM
Alex Narváez
Alex Narváez - avatar
+ 1
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { int number = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(Sum(number)); } static int Sum(int num) { //complete the recursive method so: if (num == 0) { return 0; } return num + Sum(num - 1); } } }
18th Feb 2023, 6:49 PM
Guy Martial KEYOU
0
show us your try wich give error, so we could help you to correct it ;)
26th Jun 2021, 3:00 AM
visph
visph - avatar
0
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { int number = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(Sum(number)); } static int Sum(int num) { //completa el método recursivo if (num == 5) { return 5; } return num + Sum(num + 5); } } }
26th Jun 2021, 3:09 AM
Alex Narváez
Alex Narváez - avatar