I want to print prime numbers between 1 to 100, I write my code like the following but when I run it, it starts printing 3,7,11,17....91 Why not the code print 2? Please help me friends
#include <stdio.h>
int main(void)
{
for(int i=2;i<100;i++)
{
for(int j=2;j<i;j++)
{
if(i%j==0)
break;
else if(i==j+1)
printf("%d\n",i);
}
}
}
The condition i==j+1
will not be true for i==2
. This can be fixed by a couple of changes to the inner loop:
#include <stdio.h>
int main(void)
{
for (int i=2; i<100; i++)
{
for (int j=2; j<=i; j++) // Changed upper bound
{
if (i == j) // Changed condition and reversed order of if:s
printf("%d\n",i);
else if (i%j == 0)
break;
}
}
}
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j;
int b=0;
for (i=2;i<=100;i++){
for (j=2;j<=i;j++){
if (i%j==0){
break;
}
}
if (i==j)
print f("\n%d",j);
}
getch ();
}
#include <stdio.h>
int main () {
int i, j;
for(i = 2; i<100; i++) {
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime", i);
}
return 0;
}
#include<stdio.h>
main()
{
int i,j,k;
for(i=2;i<=100;i++)
{
k=0;
for(j=2;j<=i;j++)
{
if(i%j==0)
k++;
}
if(k==1)
printf("%d\t",i);
}
}
Source: Stackoverflow.com