1

so my task is as follows: Construct a do-while() loop, which continues to prompt the user for an integer, and determines the sum of integers entered, until a prime number is encountered. The prime number should not be included in the sum. Show all variable declarations.

I have all of the variable add up correctly however cannot seem to get the function to stop on a prime number. To try to correct this I made the variable "primecheck" and set it to 2++ thinking that it would be every integer above 2 (obviously not possible but one could hope). any assistance would be much appreciated!

int main (void)
{
    int sum = 0, num = 0, i = 0, primecheck = 0, two = 2;

    primecheck = two++;
    do
    {
            printf ("Enter an integer: ");
            scanf ("%d", &num);
            if (num % primecheck == 0 && primecheck != num)
            {
                sum += num;
            }
    } while (num % primecheck == 0 && primecheck != num);

    i = sum;
    printf("%s%d%s", "Sum = ", i, "\n");

}
Codor
  • 17,447
  • 9
  • 29
  • 56
Dillon J.
  • 23
  • 3
  • 5
    `two = 2`, `two++`. I know "magic" numbers are bad, but really? Especially because now `two == 3`. – Jon Egeland Feb 25 '15 at 06:03
  • 1
    Doesn't primecheck have to change value inside the loop? – Marichyasana Feb 25 '15 at 06:07
  • 2
    I don't understand how the primality check is supposed to work in the implementation. – Codor Feb 25 '15 at 06:10
  • @codor actually, yeah I don't think that method will work with this ( maybe it will sorry my knowledge is very limited) but it has to be a single function and a do-while loop. basically the loop should not run if the number entered is prime – Dillon J. Feb 25 '15 at 06:15

1 Answers1

1

One possibility would be to introduce a function which performs the primality check, which could be done by using check divisions by all smaller numbers and terminate the loops as soon as a prime number is found. An implementation can be found following this link; the code can be refactored to the follwing function for primality testing. The function returns 1 if n is prime and 0 otherwise. The implementation uses an explicit while loop as the requirements apparently demands it.

int is_prime(int n)
{
    int i=3;
    int flag=0;
    if (n%2==0)
    {
        return 0;
    }
    do
    {
        if (n%i==0)
        {
            flag=1;
            break;
        }
        i+=2;
    }
    while (i*i<=n);
    return flag;
}
Codor
  • 17,447
  • 9
  • 29
  • 56