1

I'm very new to programming and I was asked to find the sum of prime numbers in a given range, using a while loop. If The input is 5, the answer should be 28 (2+3+5+7+11). I tried writing the code but it seems that the logic isn't right.

CODE

#include <stdio.h>
int main()
{
    int range,test;
    int sum = 2;
    int n = 3;
    printf("Enter the range.");
    scanf("%i",range);
    while (range > 0)
    {
        int i =2;
        while(i<n)
        {
            test = n%i;
            if (test==0)
            {
             goto end;
            }
                  i++;
        }
        if (test != 0)
        {
            sum = sum + test;
            range--;
        }
        end:
                  n++;
    }
    printf("The sum is %i",sum);
    return 0;
}

It would be nice if you could point out my mistake and possibly tell me how to go about from there.

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Shail
  • 881
  • 9
  • 20
  • 37
  • 2
    Just a quick code quality comment - don't use goto. – Shade Feb 07 '13 at 08:23
  • 1
    use `break`instead and remove `end:` and it should work like before – scones Feb 07 '13 at 08:24
  • I looked at your code at glance, and found label "end" there, as far as I remember usage of labeles is considered a bad style because it makes code revision very complicated – spin_eight Feb 07 '13 at 08:25
  • ya just remove goto label and it should work. – shalki Feb 07 '13 at 08:27
  • For the example 5 in your question, what is the _actual_ output? – Some programmer dude Feb 07 '13 at 08:28
  • 2
    If you need to get the sum of primes, why are you adding the remainder of the last trial division instead? (sum = sum +test) instead of (sum=sum+n) – Aki Suihkonen Feb 07 '13 at 08:29
  • @JoachimPileborg The output should be "28". – Shail Feb 07 '13 at 08:35
  • @AkiSuihkonen Yes, you have a point. It should be sum=sum+n. – Shail Feb 07 '13 at 08:36
  • I didn't ask what the _expected_ output was, but the _actual_. – Some programmer dude Feb 07 '13 at 08:37
  • @Shade I've seen plenty of commercial code in C, use `goto` – Aniket Inge Feb 07 '13 at 10:58
  • @Aniket, that doesn't mean it's good practice. Unless you like unmaintainable code, that is. – Shade Feb 07 '13 at 14:21
  • @shade, using goto a **little** is an _ok_ practice. nothing too unmaintainable about that – Aniket Inge Feb 07 '13 at 14:24
  • @Aniket, OK, I'm not a C programmer and have only read about goto and why you should never use it. However, when you start using *a little* then things start getting bad already - how much is a little? Once every few lines? Once per function? And why can't you structure your code in a better way, rather than take shortcuts? See http://stackoverflow.com/questions/46586/goto-still-considered-harmful for more info (if you feel like it, though). – Shade Feb 07 '13 at 14:30

5 Answers5

4

first of all, in the scanf use &range and not range

scanf("%i",&range);

Second this instruction is not correct

sum = sum + test;

it should be

sum = sum + n;

and also the

while (range > 0)

should be changed to

while (range > 1)

Because in your algorithm you have already put the first element of the range in the sum sum = 2 so the while should loop range - 1 times and not range times

That's all

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

OK, my C is really bad, but try something like the following code. Probably doesn't compile, but if it's a homework or something, you better figure it out yourself:

UPDATE: Made it a while loop as requested.

#include <stdio.h>
int main()
{
    int range, test, counter, innerCounter, sum = 1;
    int countPrimes = 1;
    int [50] primesArray;
    primesArray[0] = 1;

    printf("Enter the range.");
    scanf("%i",range);

    counter = 2;
    while (counter <= range) {
        for (innerCounter = 1; innerCounter < countPrimes; innerCounter++) {
            if (counter % primesArray[innerCounter] == 0)
                continue;
            primesArray[countPrimes + 1] = counter;
            countPrimes ++;
            sum += counter;
        }

        counter ++
    }

    printf("The sum is %i",sum);
    return 0;
}
Shade
  • 9,936
  • 5
  • 60
  • 85
0

I haven't done C in a while, but I'd make a few functions to simplify your logic:

#include <stdio.h>
#include <math.h>

int is_prime(n) {
    int i;

    for (i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return 0;
        }
    }

    return 1;
}

int main() {
    int range, i, sum, num_primes = 0;

    printf("Enter the range: ");
    scanf("%d", &range);

    for (i = 2; num_primes < range; i++) {
        if (is_prime(i)) {
            sum += i;
            num_primes++;
        }
    }

    printf("The sum is %d", sum);

    return 0;
}

Using goto and shoving all of your code into main() will make your program hard to debug.

Blender
  • 289,723
  • 53
  • 439
  • 496
0

Try the simplest approach over here. Check C program to find sum of all prime between 1 and n numbers.

CODE

#include <stdio.h>

int main()
{
    int i, j, n, isPrime, sum=0;

    /*
     * Reads a number from user
     */
    printf("Find sum of all prime between 1 to : ");
    scanf("%d", &n);

    /*
     * Finds all prime numbers between 1 to n
     */
    for(i=2; i<=n; i++)
    {

        /*
         * Checks if the current number i is Prime or not
         */
        isPrime = 1;
        for(j=2; j<=i/2 ;j++)
        {
            if(i%j==0)
            {
                isPrime = 0;
                break;
            }
        }

        /*
         * If i is Prime then add to sum
         */
        if(isPrime==1)
        {
            sum += i;
        }
    }

    printf("Sum of all prime numbers between 1 to %d = %d", n, sum);

    return 0;
}
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Pankaj Prakash
  • 2,300
  • 30
  • 31
0

Copy - pasted from here.

#include <stdio.h>

  int main() {
        int i, n, count = 0, value = 2, flag = 1, total = 0;

        /* get the input value n from the user */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* calculate the sum of first n prime nos */
        while (count < n) {
                for (i = 2; i <= value - 1; i++) {
                        if (value % i == 0) {
                                flag = 0;
                                break;
                        }
                }
                if (flag) {
                        total = total + value;
                        count++;
                }
                value++;
                flag = 1;
        }

        /* print the sum of first n prime numbers */
        printf("Sum of first %d prime numbers is %d\n", n, total);
        return 0;
  }

Output:

Enter the value for n:5
Sum of first 5 prime numbers is 28
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67