C# Example of Sum of Even Numbers from 1 to 100
Below is an example that gives the sum of even numbers between 1 and 100 (including 100) in the C# programming language.
namespace ConsoleApplicationTest
{
class Program {
static void Main(string[] args) {
int total = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
total += i;
}
}
Console.WriteLine(total);
Console.ReadLine();
}
}
}
Between 1 and 100 (including 100) the "for loop" is executed. Inside the loop, it is checked whether the value incremented by 1 each time (variable i) is divided by "%2" by 2 (i % 2 == 0 Here means the remainder of the division by 2 is zero?). If the result is "true", our variable "i" is cumulatively added to our variable "sum", which is defined outside of the loop and collects the values.
The result would be 2550..