Please help me with the task: Sum them all

Hello, I’m working on this task:

Create a class that has one public static method, GetSumBetween, that takes two integers, a and b, and returns as an integer the sum of all integers between a and b (including a and b). In the Main method, read two integers from the console, call GetSumBetween, and print the returned number to the console.
For example (don’t output the green text):
>6
>10
40 // 6 + 7 + 8 + 9 + 10 = 40

Here is my code:


namespace Static
{
   
   class Mine
   {
       public static int Sum;
       public static void GetSumBetween(int a, int b)
       {
           for (int i=a; i<=b; i++)
           {
               Mine.Sum = Mine.Sum + i;
           }
       }
   }

   class SumThemAll
   {
       public static void Main()
       {
           int a = int.Parse(Console.ReadLine());
           int b = int.Parse(Console.ReadLine());
           Mine.GetSumBetween(a, b);

           Console.WriteLine(Mine.Sum);
       }
   }
}

Can anyone please help me to solve it?

method GetSumBetween should return a sum. you return nothing (void)
you don’t need a static variable int Sum - you can easily move it inside GetSumBetween() as a usual:

int Sum = 0;
1 Like

I gess that problem is here Create a class that has one public static method, GetSumBetween, that takes two integers, a and b, and returns as an integer the sum of all integers between a and b (*including* a and b)

Your method return void. And in the task we need to return int.
P. S. Lena is so fast ^-^

1 Like

Дякую, Лена і Мария! Але поки не вирішила, мабуть в мене пробіли в темі.
Ось мій новий код.
using System;

namespace Static
{

class Mine
{
    public static int GetSumBetween(int a, int b)
    {
        int sum = 0;
        for (int i=a; i<=b; i++)
        {
            sum = sum + i;
        }
        return sum;
    }
}

class SumThemAll
{
    public static void Main()
    {
        int a = int.Parse(Console.ReadLine());
        int b = int.Parse(Console.ReadLine());
        Mine.GetSumBetween(a, b);

        Console.WriteLine(Mine.sum);
    }
}

}

Console.WriteLine(Mine.sum);

всі внесені змінні вірні! але цей рядок треба замінити, бо виводити треба результат метода. Mine.GetSumBetween(a, b), а не статичну змінну Mine.sum

1 Like