Put more conditions into for loop to generate prime numbers. - C Statement

C examples for Statement:for

Description

Put more conditions into for loop to generate prime numbers.

Demo Code

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
   int primes[50], primeIndex = 2;
   bool isPrime;// w  w w  .j a  v  a2  s .  c  o  m

   primes[0] = 2;
   primes[1] = 3;

   for (int p = 5; p <= 50; p = p + 2)
   {
      isPrime = true;

      for (int i = 1; isPrime && p / primes[i] >= primes[i]; ++i)
         if (p % primes[i] == 0)
            isPrime = false;

      if (isPrime == true)
      {
         primes[primeIndex] = p;
         ++primeIndex;
      }
   }

   for (int i = 0; i < primeIndex; ++i)
      printf("%i ", primes[i]);

   printf("\n");

   return 0;
}

Result


Related Tutorials