Yesterday we studied about functions, so today lets write code to print prime numbers in a range using function.
Lets start with the first writing a function to print prime numbers:

What we did in this code was, first we made a function prime with void as return type. We then created a variable count and initialized it to zero. This counter variable was made to count the number of times a number is divisible by any num other than 1 or itself to check if it's prime or not. Every time the number becomes fully divisible by some other num the value of this counter variable increases so at first we initialized it to 0, and then increment it after checking the condition.
For checking this condition we made a for loop which starts from 2 till squareroot of the number (for optimization), we could have also continued the loop until the number, then in the loop we checked the remainder on dividing the number with every num and if it comes as zero, it means the number is completely divisible by that number and hence the number is not prime.
Once we find a single number that can completely divide the number to be checked for prime, we increment the value of count and break the loop.
Then we check if the value of count still remains zero or not. If count = 0, till the end of loop it means the number wasn't divisible by any other number and therefore it's prime and so we print the number.
We could have checked if the number is prime or not by another way as well

In this we chose the return type as boolean and then repeated the same loop as we did earlier but this time instead of making a variable counter we directly return true or false to the caller (as the returntype is boolean)
Now so far we wrote the code to check if a number is prime or not, but we need to print all the prime numbers in the mentioned range. So for this let's write another function that would use one of these functions to check if a number is prime or not and then print all the prime numbers that come in the range.
So in this we wrote function with returntype as void again, which takes two numbers as parameters and then runs a loop from the first number to the second number and inside it, calls the isPrime function and after checking if the number is prime or not it prints them.
Then in the main method we provide the variables and call the range method.

Top comments (0)