After several hours I have figured this out, but because the % statement is confusing to me I was wondering if someone wolud not mind explaining to me my for statement in the following program?

``````using System;

/*This program is designed to identify the prime numbers from 1 to 100.  Then total their sum and find the average of the prime numbers from 1 to 100.*/

{
/* Main method entry point*/
public static void Main()
{
/*declare variables*/
int num = 2,
x;
double countPrimeNum = 0,
avg;

/*while loop, which determines when num <= 100 (or 2 <= 100).*/

while (num <= 100)
{
bool isPrime = true;
/*test num to see if it is prime*/
for (x = 2; x < num; ++x)
{
if ((num % x) == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
/* List the prime number, once the program determines a number is prime*/
Console.WriteLine (num);
}
//Add 1 to the number and then go to the begining of the loop and test to see wether to re-enter the loop or to go to the next step*/
++num;
}
Console.WriteLine ("The average of the prime numbers between 2 to 100 is: {0}", avg);
}

}
``````

## All 4 Replies

The % operator, or modulo operator returns the remainder when you divide the numbers.
Ex. 5%2 = 1
4 % 2 = 0

In your code the statement if ((num % x) == 0) checks to see if num is divisible. If it is, the number is obviously not prime.

Still confused. In the for statement for (x = 2; x < num; ++x)
what I am I saying??

And then for the modulus if I understand you correctly? The prime number is false, when the number does not evenly divide into the number below it?? example
33/32 = 1.03125 Therefore since it doesn't divide evenly it has a modulus of 1. Is that correct???

the for construct can be looked at like a while construct. Maybe this will help you understand it
x=2;
num = 100;
while ( x < num )
{
// do something with x
x = x + 1;
}

Hope that helps.
The modulus returns the remainder of the division. 33/32 = 1.03125 (remainder is .03125)

Thanks,
For the help guys. I think I have a much better understanding.

the for construct can be looked at like a while construct. Maybe this will help you understand it
x=2;
num = 100;
while ( x < num )
{
// do something with x
x = x + 1;
}

Hope that helps.
The modulus returns the remainder of the division. 33/32 = 1.03125 (remainder is .03125)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.