Q-06: Write a function to find whether a given number is prime or not. Use the same function to generate all the prime numbers less than 100.
    

Using - C


#include<stdio.h> int checkPrime(int x); void printPrime(int range_start, int range_end); void main(){ int n,i; printf("Enter a number: "); scanf("%d",&n); if(checkPrime(n)) printf("%d is a prime number!\n",n); else printf("%d is not a prime number!\n",n); printf("\nPrinting all Prime Numbers upto 100: \n"); printPrime(1,100); } int checkPrime(int x) { int i; if(x==1 || x==0) // So that Program won't crash return 0; else { for(i=2; i <= x/2; i++) { if(x%i==0) { return 0; } } } return 1; } void printPrime(int range_start, int range_end) { int i; for(i=range_start; i <= range_end; i++) { if(checkPrime(i)==1){ printf("%d ",i); } } }

OUTPUT

Enter a number: 11
11 is a prime number!
  
Printing all Prime Numbers upto 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
        

Using - C++


#include<iostream> using namespace std; class PrimeNumbers{ public: int checkPrime(int x); void printPrime(int range_start, int range_end); }; int PrimeNumbers::checkPrime(int x) { if(x==1 || x==0) // So that Program won't crash return 0; else { for(int i=2; i <= x/2; i++) { if(x%i==0) { return 0; } } } return 1; } void PrimeNumbers::printPrime(int range_start, int range_end) { for(int i=range_start; i <= range_end; i++) { if(checkPrime(i)==1) { cout<< i<< " "; } } } int main(){ int n; PrimeNumbers object; cout<< "Enter a number: "; cin>> n; if(object.checkPrime(n)) cout<< n<< " is a prime number!"<< endl; else cout<< n<< " is not a prime number!"<< endl; cout<< "\nPrinting all Prime Numbers upto 100: "<< endl; object.printPrime(1,100); return 0; }

OUTPUT

Enter a number: 8
8 is not a prime number!
  
Printing all Prime Numbers upto 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