Programs of Loops

Find prime numbers and traverse arrays in a circular manner.

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 22 as the first prime number at the 0th0^{th} index.
  • Keep checking every following integer by dividing it by every prime value in the array.
    • Check 33 by taking the remainder after dividing it by all the prime values in the array. The only value in the current array is 22. Since the remainder is non-zero, 33 is stored in the array.
    • Then, check 44 in the same way. Since the remainder of 44 divided by 22 is 00, 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.