Outer for loop selects number one by one for each iteration. We initialize num to 2 and for each iteration num value increments by 1. Outer for loop executes until num is less than or equal to user entered limit times.
Inner For loop Logic
All the numbers are perfectly divisible by number 1, so we initialize the variable count to 2, instead of 1. So our inner for loop starts checking for divisibility from number 2.
The selected number(selected by outer for loop and stored in variable num), is divided by numbers 2 to num-1 times. If num is perfectly divisible by any number between 2 to num-1, then the number is not a prime number, else its a prime number.
Source Code: C Program To Find Prime Numbers From 2 To N, using For Loop
Note: We are not using curly braces around if statement because we only have 1 line of code after if – so curly braces are optional. If we have multiple lines of code, then we must use curly braces to wrap around the block of code.
All the numbers are perfectly divisible by number 1, so we initialize the variables start and count to 2, instead of 1. So our c program starts checking for divisibility from number 2.
Source Code: C Program To Find Prime Numbers From 2 To N, using Nested While Loop
Logic To Find Prime Numbers From 2 To N, using While Loop
In this method, we apply square root to the user entered number and store it inside variable inum. This reduces the number of iterations of inner while loop.
For example, If num = 100; inum = sqrt(num); inum = sqrt(100); inum = 10;
User entered number 100 is perfectly divisible by 5 and 10, so number 100 is not a prime number.
So its enough if we iterate through the while loop sqrt(num) times to check if the user entered number is divisible by any number other than 1 and itself.
We start checking for prime number from number 2 till the user entered number. Variable start is assigned an initial value of 2. For each iteration of outer while loop value of start increments by 1. Inside the inner while loop we check if the value present in variable start is prime number or not. If its prime number then we print that number on to the console window.
Outer while loop selects the number and stores it in variable start on each iteration. Inner while loop checks if the selected number(present in variable start) is prime number or not. You can know the complete logic to check whether a selected number is prime or not: C Program To Find Prime Number or Not using While Loop
Table of all prime numbers up to 1,000:
Note: We are not using curly braces around if statement because we only have 1 line of code after if – so curly braces are optional. If we have multiple lines of code, then we must use curly braces to wrap around the block of code.