0
# include <stdio.h>

int main()
{
    int i,p,f=1;
    printf("Prime Numbers till 99: \n");
    for (p=2;p<99;p++)
    {
        for (i=2;i<p;i++)
            if(p%i==0)
            {
                f=0;
                break;
            }

        if(f=1)
            printf("%d ",p);
    }
    return 0;
}

Why am i not getting the prime numbers instead getting all the numbers from 2 to 98 ?

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
Aman Singh
  • 743
  • 1
  • 10
  • 20
  • 4
    This question appears to be off-topic because it is predicated upon a typo and will have no relevance for future readers. – jscs Jul 19 '13 at 19:56
  • @JoshCaswell There is slightly more than that one typo, but you are right in that it will likely not be of much relevance to anyone in the future. – arshajii Jul 19 '13 at 19:59
  • Multiple errors of that sort really only decrease the likelihood of usefulness, @arshajii, since the chance that someone else makes the same combination goes down. – jscs Jul 19 '13 at 20:02
  • @JoshCaswell I do agree, and voted to close accordingly. – arshajii Jul 19 '13 at 20:04
  • if you might do `if(1==f)` instead of `if(f==1)` then misspelled `=` instead of `==` will give an error Read: [Variable assignment in `“if”` condition](http://stackoverflow.com/questions/17681535/variable-assignment-in-if-condition/17681607#17681607) – Grijesh Chauhan Jul 19 '13 at 20:33

2 Answers2

3

There are two mistakes here.

  1. if (f=1) needs to be if (f==1) or simply if (f). Remember, = is assignment; == is comparison.
  2. You need to set f back to 1 at the end of each loop iteration. Otherwise f will be 0 forever after the innermost if-statement is first entered, and only the first prime number will be printed.

int main() { 
    int i, p, f = 1;
    printf("Prime Numbers till 99: \n");

    for (p = 2; p < 99; p++) {      
        for (i = 2; i < p; i++) {
            if (p%i == 0) {
                f = 0;
                break;
            }
        }

        if (f) {  // here
            printf("%d ", p);
        }

        f = 1;  // and here
    }

    return 0;
}
Prime Numbers till 99: 
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
arshajii
  • 127,459
  • 24
  • 238
  • 287
1

if(f=1) should read if(f==1). The assignment always evaluates true.

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92