Programs of Loops
Find prime numbers and traverse arrays 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 to 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
n
elements. - 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.
Note: We have added a helper function
printArray
to assist us in printing the array. We only need to pass the array and its size as arguments to the function and it will print the array.
Get hands-on with 1400+ tech skills courses.