+ 1

Why is my program printing more prime no.s than those which are expected | Basic C Programming

https://code.sololearn.com/cQZudLLXtQpm/?ref=app I’ll be really grateful if some one out there spare some time to check my code and spot the error in this simple basic code.

2nd Sep 2019, 10:05 AM
Aditya Singh
Aditya Singh - avatar
3 odpowiedzi
+ 1
The problem lies in this line 👇 scanf("enter a number %d", &n); If you work with that, then suppose you want to print prime numbers upto 20, your input should be "enter a number 20" You can try this instead scanf("%d enter a number", &n); Now you only need to input a number But it's better if you do this 👇 printf("enter a number \n"); scanf("%d", &n); #include <stdio.h> int main() { int n,i,j,k; printf("enter a number \n"); scanf("%d", &n); printf("Prime numbers are: \n"); for (i=2; i<=n; i++) { k=0; for (j=2; j<i; j++) { if (i%j==0) { k=1; } } if (k==0) { printf("%d\n", i); } } }
2nd Sep 2019, 11:25 AM
Baribor Saturday
Baribor Saturday - avatar
+ 1
2nd Sep 2019, 10:21 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
Baptiste E. Prunier Never thought use of scanf in a little different way can disturb the output so interestingly. Thank ypu
2nd Sep 2019, 10:26 AM
Aditya Singh
Aditya Singh - avatar