Object

Write a program to print all prime numbers up till a specified range.

Algorithm

  1. Declare integer variables a, b and num.
  2. Read num.
  3. Set a = 2.
  4. Repeat WHILE a <= num
    • Set b = 2.
    • Repeat WHILE b < a
      • IF a mod b = 0, then
        • Break out of loop.
      • ELSE
        • b++.
      • [End of IF-ELSE structure.]
    • [End of inner WHILE loop.]
    • IF a = b, then
      • Write a
    • [End of IF structure.]
    • a++.
    • [End of outer WHILE loop.]
  5. Exit.

Flowchart

C++ Source Code

// program 59
#include<iostream>
using namespace std;

int main()
{
  int a, b, num;

  cout << "Enter the number: ";
  cin >> num;
  a = 2;

  while (a <= num)
  {
    b = 2;
    while (b < a)
    {
      if (a % b == 0)
        break;
      else
        b++;
    }

    if (a == b)
      cout << a << "\t";
    a++;
  }
  return 0;
}

C Source Code

/*program 59*/
#include<stdio.h>

int main()
{
  int a, b, num;

  printf("Enter the number: ");
  scanf("%d", &num);
  a = 2;
  while(a<=num)
     {
     b = 2;
     while(b<a)
	{
	if(a%b==0)
	  break;
	else
	  b++;
	}
     if(a==b)
       printf("%d\t", a);
     a++;
     }
  return 0;
}

Output

Enter the number: 100
2       3       5       7       11      13      17      19      23      29      31      37      41      43      47     53       59      61      67      71      73      79      83      89      97
Design a site like this with WordPress.com
Get started