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. Repeat FOR a = 2 to num by 1
    • Repeat FOR b = 2 to (a-1) by 1
      • IF a mod b = 0, then
        • Break out of loop.
      • [End of IF structure.]
    • [End of inner FOR loop.]
      • IF a=b, then
        • Write a.
      • [End of IF structure.]
    • [End of outer FOR loop.]
  4. Exit.

Flowchart

C++ Source Code

// program 42
#include <iostream>
using namespace std;
int main()
{
  int a, b, num;

  cout << "Enter the number: ";
  cin >> num;
  for (a = 2; a <= num; a++)
  {
    for (b = 2; b < a; b++)
    {
      if (a%b==0)
      break;
    }
    if (a==b)
      cout << a << "\t";
  }
  return 0;
}

C Source Code

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

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

  printf("Enter the number: ");
  scanf("%d", &num);
  for(a=2; a<=num; a++)
     {
     for(b=2; b<a; b++)
	 {
	 if(a%b==0)
	 break;
	 }
     if(a==b)
       printf("%d\t", 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