C# Program to find the sum of prime numbers between 1 to n


In this program, You will learn how to find the sum of prime numbers between 1 to n in C#.


10th => 2 + 3 + 5 + 7 = 17

Example: How to find the sum of prime numbers between 1 to n in C#.

using System;
public class Program
{
	public static void Main(string[] args)
	{
		int n, i, p, k, s = 0;

		Console.Write("Enter a number:");
		n = Convert.ToInt32(Console.ReadLine());

		for (i = 2; i <= n; i++)
		{
			k = 2;
			p = 1;
			while (k < i)
			{
				if (i % k == 0)
				{
					p = 0;
					break;
				}
				k++;
			}
			if (p == 1)
			{
				s = s + i;
			}
		}

		Console.WriteLine("Sum of prime numbers:" + s);
	}
}

Output:

Enter a number:10
Sum of prime numbers:17