how to calculate the sum of even number in csharp

To calculate the sum of even numbers in C#, you can use a loop to iterate through a range of numbers and add the even numbers to a running sum.

Here's an example code snippet:

main.cs
int sum = 0;
for (int i = 0; i <= 100; i++)
{
    if (i % 2 == 0)
    {
        sum += i;
    }
}
Console.WriteLine("The sum of even numbers is {0}", sum);
156 chars
10 lines

This code calculates the sum of even numbers between 0 and 100. The variable sum is initially set to 0, and then the loop iterates through each number from 0 to 100. If the number is even (i.e., its remainder when divided by 2 is 0), it is added to the sum variable. The final result is printed to the console.

You can adjust the range of numbers or the starting point to suit your needs.

related categories

gistlibby LogSnag