Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m taking a C programming course & my professor gives us programming exercises

ID: 3594983 • Letter: I

Question

I'm taking a C programming course & my professor gives us programming exercises at the end of class. The one we had today was:

Sieve of Eratosthenes Algorithm To Display All Prime Numbers Between 1 and n
Step 1: Define an array of integers P. Set all elements Pi to 0, 8 <= i <= n.
Step 2: Set i to 8.
Step 3: If i > n, the algorithm terminates.
Step 4: If Pi is 0, then i is prime.
Step 5: For all positive integer values of j, such that i * j n, set Pi*j to 1.
Step 6: Add 1 to i and go to step 3.

This is what I have:

#include <stdio.h>

int main(void)

{

//Declare Variables

int P[121], i, n;

P[i] = 0;

8 <= i <= n;

i = 8;

//Initialize 'if' & 'else' decision making.

if (i > n)

{

printf("End of Program. ");

}

else (P[i] = 0);

{

printf("%i is Prime.", i);

}

return 0;

}

I need help with my code, everything is here in the steps clearly but I don't know how to put it all together.

Explanation / Answer

your program is wrong completely. Below is the working program for this algorithm

#include <stdio.h>
#include <stdlib.h>

#define limit 20 /*size of integers array*/

int main(){
unsigned long long int i,j;
int *primes;
int z = 1;

primes = malloc(sizeof(int) * limit);

for (i = 2;i < limit; i++)
primes[i] = 1;

for (i = 2;i < limit; i++)
if (primes[i])
for (j = i;i * j < limit; j++)
primes[i * j] = 0;

printf(" Prime numbers in range 1 to %d are: ",limit);
for (i = 2;i < limit; i++)
if (primes[i])
printf("%d ", i);

return 0;
}

Output


Prime numbers in range 1 to 20 are:
2
3
5
7
11
13
17
19