I'm trying to find the sum from (1 to n) or given number. using this code:
int n;
int counter = 0;
int sum = 0;
Console.Write("Please enter the sum limit number: ");
n = int.Parse(Console.ReadLine());
//around here is where code freezes and nothing else happens
while(counter <= n)
{
counter = +1;
sum = sum + counter;
}
Console.Write("The sum from 1 - " + n + " =" + sum);
I know I can use:
int n;
int counter = 0;
int sum = 0;
Console.Write("Please enter the sum limit number: ");
n = int.Parse(Console.ReadLine());
var sum = Enumerable.Range(1, n);
Console.Write("The sum from 1 - " + n + " =" + sum.Sum());
but my next challenge is to only add the numbers that are divisible by 3 or 5, so I'm planning on doing:
if (sum % 3 == 0 | sum % 5 == 0)
{
total = total + sum;
}
What is wrong with my method? Also, alternative ways to do this are more than appreciated!