Monday, January 18, 2021
Home Loops in C++ Prime Numbers Generation in C++

Prime Numbers Generation in C++

prime numbers[AdSense-A]
Now implementing this logic of Prime Numbers into our c++ code, we need simple for loops and conditional statements. This is very easy to implement and print Prime Numbers upto 1000. Lets have a look at the following code:

  1. //Prime Numbers generation in C++
  2. //Using for loops and conditional structures
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.     int a = 2;       //start from 2
  9.     long long int b = 1000;     //ends at 1000
  10.  
  11.     for (int i = a; i <= b; i++)
  12.     {
  13.  
  14.      for (int j = 2; j <= i; j++)
  15.      {
  16.         if (!(i%j)>>(i!=j))    //Condition for not prime
  17.             {
  18.                 break;
  19.             }
  20.  
  21.         if (j==i)             //condition for Prime Numbers
  22.             {
  23.                   cout << i << endl;
  24.  
  25.             }
  26.      }
  27.     }
  28. }

Now lets explain this code, first of all we defined two variables that defined our limits upto which we are going to print Prime Numbers. The most important thing is using the “conditional statement ” inside the nested for loops. We used a condition that if the variables inside the loop do not have true modulus and both the variables are not equal then break, otherwise if both variables are equal then it is a Prime Number, and print it.
[AdSense-B]

 

- Advertisment -

Most Popular

Android Webview Tutorial With Example | How to Use Webview in Android

Android Webview Tutorial With Example Have you seen an Android app displaying Web content using Webview. This Android Webview Tutorial is about integrating Webview using Android Studio....

Student Registration Project in PHP

In this Student Registration Project we are providing a form in simple html to the student and that form sends the data to "student.php"...

Java GUI Calculator Source Code

Here we have a Java GUI Calculator Source Code for you in which a Java GUI calculator has been created using "swing" and "awt". The calculator has...

Numeric Array in PHP

Numeric arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero....