Started learning C# second time. I have written a console program to calculate sum and count of even and odd numbers. Provided code :
using System;
namespace Studying_
{
class Program
{
static void Main(string[] args)
{
uint evenNumbersCount = 0;
uint oddNumbersCount = 0;
int sum = 0;
Console.WriteLine("Enter the first number in the range to find out it odd or even. The program won't count numbers you entered in the sum");
int numberOne = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number");
int numberTwo = int.Parse(Console.ReadLine());
if (numberTwo < numberOne)
{
int a = numberTwo;
numberTwo = numberOne;
numberOne = a;
}
while(numberOne < numberTwo - 1)
{
numberOne++;
int result = numberOne % 2;
sum += numberOne;
switch (result)
{
case 0:
evenNumbersCount++;
break;
case 1:
oddNumbersCount++;
break;
}
}
Console.WriteLine("Sum - " + sum + " | Even - " + evenNumbersCount + " | Odd - " + oddNumbersCount);
Console.ReadKey();
}
}
}
Input : 2, 5
Output : "Sum - 7 | Even - 1 | Odd - 1
2 and 5 aren't counted
Is this code good? Can I improve it or optimize?
P.S. Sorry for my english and if I did something off-topic. Let me know if something is wrong.
evens = n - odds
wheren
is the length of the range? Obviously the whole thing here could be reduced to closed-form so you don't need to loop. (Odd and even are both aboutn/2
, with adjustments based on the first and last numbers. And Gauss'sn * (n+1)/2
for the sum of 1..n can be adapted for a range, and also done without possible overflow if necessary, like clang does when optimizing asum+=i
loop like this. But I'm guessing that these are placeholders for real work.) \$\endgroup\$