To print all prime numbers in given range. Example Input lower limit: 1 Input upper limit: 20 Output Prime numbers between 2, 3, 5, 7, 13, 17, 19 Required knowledge What is Prime number? Prime numbers are those numbers that can only be divisible by 1 and itself. Let us modify the above program to work for prime numbers in given range.
Run a loop from 2 to end, increment 1 in each iteration. For example: 2, 35, 7, 11 are the first five prime numbers.
That is, if a number is not divisible by anything except 1 and the number itself is called as prime number. That is, if the number is 17, then check upto 16 then exit from the loop, and check for next number say 18 On exiting from the inner for loop with or without using break statement Check whether the variable count holds its original value that is 0 or not If it holds, then the number is not divisible by anything, it means that the number is prime number And if the number is prime number, then print the number as output and continue If it does not holds its original value that is 0then the number is divisible by something, it means that the number is not a prime number Never forgot to initialize 0 to count at last of the first for loop Now let's modify the above program with adding some extra features.
Prime number is a positive integer greater than 1 that is only divisible by 1 and itself. Inside the loop for each iteration print value of i if it is prime number. You can easily modify the program to work for any range. Here in this program we've adde to allow user to provide the range under which all the prime numbers are printed.
Logic to print prime numbers between 1 to n Step by step descriptive logic to print all prime numbers between 1 to n.
This is the output that you will get on your output screen: Here are some of the main steps used in above program: Take a variable say count and initialize it with 0 at beginning of the program Create a for loop and start it from 1 to 50 Inside the for loop, create another for loop with different loop variable say j Start inner for loop with 2 and run upto one less than the value of outer for loop's variable say i Then inside the second for loop, create if block to check whether the number is divisible by any number from 2 to one less than the number.