Resolved method to sum up numbers between two numbers

Kevin91

New member
Joined
Feb 12, 2021
Messages
2
Programming Experience
Beginner
I am a beginner in C# programming and trying to code a function that sums up all numbers from the start to the end and If the start number is greater than the end number, the function swap the values so that the start number becomes the end number and the end number gets the value of the start number.

This is what I tried so far:

C#:
private void SumNumbers()
{
    int startNumber, endNumber;
    Console.WriteLine("\nplease enter a start number: ");
    startNumber = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("\nplease enter an end number: ");
    endNumber = Convert.ToInt32(Console.ReadLine());

    int result = 0;

    for (int i=0;i<=startNumber;i=i+1)
    {
        result = result + i;
        Console.WriteLine(i);
    }

    Console.ReadLine();
    Console.WriteLine("The sum of Numbers between " + startNumber + " and " + endNumber + " is: " + result.ToString());
    Console.ReadLine();
}

when I run the code, I get this result: The sum of Numbers between 12 and 23 is: 78

The result should be: numbers between 12 and 24 is: 210

Thanks in advance!
 
Last edited by a moderator:
You should have debugged your code and the issue would have been obvious. You're not summing numbers from startNumber to endNumber there. You're summing numbers from zero to startNumber - 1.
 
Alternative is to use Linq mehtods Enumerable.Range and Sum:
C#:
var result = Enumerable.Range(startNumber, endNumber - startNumber + 1).Sum();
 

Latest posts

Back
Top Bottom