In: Computer Science
Please comment, exactly how this program works?
#include <stdio.h>
int main()
{
int i,j;
int a[1000];
for(i=0;i<1000;i++)
a[i]=1;
for(i=2;i<1000;i++)
{
if(a[i]==1){
for(j=i+1;j<1000;j++)
{if(j%(i)==0)
a[j]=0;
}
}
}
printf("print numbers are:\n");
for(i=2;i<=1000;i++)
if(a[i]==1)
printf("%d, ",i);
}
Code With Comments:
#include <stdio.h>
int main()
{
int i,j;//This line intialize the variables i and
j
int a[1000];//This line intialize the array with the
length of 1000 elements
for(i=0;i<1000;i++)//This loop used to assign 1 to
the all the indexs in the array
a[i]=1;
for(i=2;i<1000;i++)//This loop runs from the second
index position of the array to the end of the array
{
/*
This below if condition checks
weather the a[i]==1 or not if a[i]==1 then it runs the below loop
else loop not executed
*/
if(a[i]==1){
/*
Suppose assume
that if i=2 the below loop runs from the index position i+1 to 999
means 3 to 999
*/
for(j=i+1;j<1000;j++)
{
/*This condition checks if j is divisible by I
or not if yes then a[j]=0
in the above we have assumed
that i=2 and now in the first iteration j=3 it checks 3%2==0
or not if yes then a[j] means
a[3]=0
*/
if(j%(i)==0)
a[j]=0;
}
}
}
printf("print numbers are:\n");
/*
The below loop runs from the 2 to 1000 and prints the
index position of the array a if the value of index position is
1
*/
for(i=2;i<=1000;i++)
if(a[i]==1)
printf("%d, ",i);
}
Code snippet: