I read the sticky about helping with homework, so I hope this is ok.
I'm new to programming, and I think I have the logic correct, but it doesn't give me the correct answer.
We haven't learned arrays yet, so we have to do this using if statements and loops.
The program is supposed to find all the prime numbers between 1 and 100. Find the sum, then output the average.
Any help or suggestions would be appreciated. I'm not looking for the answer, just some help on what I'm doing wrong. Thanks.
using System;
public class PrimeNumbers
{
// Main method entry point
public static void Main()
{
// declare variables
// n starts at 2 as the first prime number
// totalPrimeNumbers starts at 1 since 2 is a prime number
// sumOfPrimes starts at 2 since 2 is the first prime number
int n = 2, totalPrimeNumbers = 1, x;
double sumOfPrimes = 2, average;
// while loop when n <= 100
while (n <= 100)
{
// test if n is prime
for (x = 2; x < n; x++)
{
if ((n % x) != 0)
{
sumOfPrimes = sumOfPrimes + n;
totalPrimeNumbers++;
// change value of x to end for loop
x = n + 1;
}
}
// increase n by 1 to test next number
n++;
}
// calculate average
average = sumOfPrimes / totalPrimeNumbers;
// display average
Console.WriteLine("The average of all prime numbers between 1 and 100 is: {0}", average);
}
}