C Program, Document everyline please Write a C program that follows this algorit
ID: 3794482 • Letter: C
Question
C Program, Document everyline please
Write a C program that follows this algorithm. Create an array of integers with values from 0 to n. Set the values at first and second index to zero. For all nonzero numbers, starting with number 2, set all multiples of it in the array to zero if they are not already zero. For example, for 2, set 4, 6, 8, ... to zero. Next for 3 set 6, 9, 12, To zero. Repeat the previous step until the last element of the array. Next, print all elements that are not zero. Are they any special numbers?!!!Explanation / Answer
Ans.
#include <stdio.h>
int main(void) {
// your code goes here
int n, i, j;
scanf("%d", &n);
int a[n+1];
for(i = 0; i < n; i++)
{
a[i] = i;
}
a[0] = 0; //first 2 elements = 0
a[1] = 0;
for (i = 2; i < n; i++) // repeating until last element
{
for (j = i + 1; j < n; j++)
{
if (j%i == 0) // checking for multiples of i
a[j] = 0;
}
}
for (i=0; i < n; i++)
{
if (a[i] !=0)
printf("%d ", a[i]);
}
return 0;
}
Special Numbers: The resultant numbers are prime numbers.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.