Programs of Loops
Find prime numbers and traverse lists in a circular manner.
We'll cover the following...
Store the first n prime numbers in the array
The following program stores the first n prime numbers in an array. The value of n is chosen by the user, and any number can be used. Here’s how to solve this problem:
- 
Start with an empty array of nelements.
- 
Store as the first prime number at the index. 
- 
Keep checking every following integer by dividing it by every prime value in the array. - 
Check by taking the remainder after dividing it by all the prime values in the array. The only value in the current array is . Since the remainder is non-zero, is stored in the array. 
- 
Then, check in the same way. Since the remainder of divided by is , it’s not stored in the array. 
 
- 
In the above code:
- 
The variable nshows the total number of prime numbers.
- 
The first ifstatement specifies that the value ofnshouldn’t be less than1.
- 
We create an array of nvalues (i.e.,Array(n)). The syntaxArray(n).fill(2)is used to create an array ofnelements, each having a value of2.
- 
We use two nested whileloops.- 
The outer loop counts the number of generated prime numbers. 
- 
The inner loop keeps generating sequential integers until the next prime number is found. 
 
- 
- 
We use the following variables: - 
nstores the total number of prime numbers.
- 
pstores the generated prime numbers.
- 
pcountkeeps track of the most recently generated prime number.
- 
vstores the next number to be tested.
- 
iiterates through the array of prime numbers generated so far.
- 
pflagindicates whether the current number is prime.
 
- 
The comments in the program itself will help explain the rest of the code.
Circular traversal
The following program demonstrates circular moves in an array using the positive numbers in that array. The program makes the value of the cell that is shown negative and ends when all values are negative.
To solve this problem, we first need to understand circular traversals.