Prime Numbers

+2 Akhilesh Chobey · November 18, 2015
How do I print prime numbers between any two given numbers?
for e.g.
Between 2 and 10

Likewise between any two numbers.
Thanks :)

Post a Reply


- page 1
Oldest  Newest  Rating
0 Jon Z. · December 11, 2015
break; only breaks out of the current inner loop.
0 Deepak Panday · November 27, 2015
int a,b,j;
prime1: while(a
this will do it..
0 Scott Walker · November 27, 2015
^^ I was going to mention that but I wasn't sure if in 'C' it would break out of both loops
+2 Jon Z. · November 26, 2015
Thanks Scott for explaining my code.

Also if you want to improve performance you can break; right after k++;. That way once k is no longer 0 you don't need to continue looping.
0 Akhilesh Chobey · November 21, 2015
Okay. Yes!
Now I get it.Thanks a lot! :)
0 Scott Walker · November 20, 2015
essentially, the incrementing of 'k' doesn't matter, it just means so at the end of the for loop 'k' is either 0 or something else, it doesn't matter if k is 1 or 64756 etc as long as it isn't 0. The if statement then checks if it's 0, if it is it prints the value as it must be a prime number. is that ok??
0 Akhilesh Chobey · November 20, 2015
Hey @Scott

. Thanks for explaining. Just one more doubt.

for 5,first k=0. 5%2 is not 0. 

Now k=1.Similarly 5%3 and 5%4 isn't zero.

So k becomes 2 and 3. Right?

How does an increment in k help us?
All other explanation is crystal clear :)
0 Carson Radtke · November 20, 2015

void printPrimes(int start, int end){
int i, j, k;
for (i=start;i
+3 Scott Walker · November 19, 2015
Essentially, the 2 parameters are your start and end, for example 5 and 10.
In the outer for loop, you assign i to the start digit (5) and say as long as it is less than 'end'(10) increment it by 1 (standard loop).

assign k to 0.

inner for loop.

whilst j is less than i, increment j by 1.

if statement: if  i (currently 5) / j (currently 2) has a remainder of 0 then increment k by 1, loop again.
                       if  i (currently 5) / j (currently 3) has a remainder of 0 then increment k by 1, loop again
                       if  i (currently 5) / j (currently 4) has a remainder of 0 then increment k by 1, loop again.

At the end of the loop, if none of the ifs were true, k will still be equal to 0 meaning it is prime, it then prints it :-).
0 Akhilesh Chobey · November 19, 2015
Hey Jon Z. thanks for that.
I am not so good with functions though. Better watch the functions tutorial again. 
However if possible could you just explain in short as to what test you performed?
Thanks again
  • 1
  • 2



One of the most popular languages of all time.

Bucky Roberts Administrator