Jumat, 08 Juli 2011

This Example Programs Calculate Prime Number Using Constructor

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the class as Prime with data members,
Member functions.
STEP 3: Consider the argument constructor Prime() with integer
Argument.
STEP 4: To cal the function calculate() and do the following steps.
STEP 5: For i=2 to a/2 do
STEP 6: Check if a%i==0 then set k=0 and break.
STEP 7: Else set k value as 1.
STEP 8: Increment the value i as 1.
STEP 9: Check whether the k value is 1 or 0.
STEP 10:If it is 1 then display the value is a prime number.
STEP 11:Else display the value is not prime.
STEP 12:Stop the program.

C++ PROGRAM:
01#include<iostream.h>
02#include<conio.h>
03class prime
04{
05                int a,k,i;
06              public:
07              prime(int x)
08              {
09                            a=x;
10              }
11              void calculate()
12              {
13                 k=1;
14                {
15                     for(i=2;i<=a/2;i++)
16 
17       if(a%i==0)
18                     {
19                              k=0;
20                              break;
21                     }
22                     else
23                    {
24                            k=1;
25                  }
26                }
27              }
28 
29void show()
30              {
31                if(k==1)
32                  cout<< “\n\tA is prime Number. ";
33                else
34                  cout<<"\n\tA is Not prime.";
35              }
36};
37 
38void main()
39{
40    clrscr();
41    int a;
42    cout<<"\n\tEnter the Number:";
43    cin>>a;
44    prime obj(a);
45    obj.calculate();
46    obj.show();
47    getch();
48}
Sample Output:
Enter the number: 7
Given number is Prime Number

Tidak ada komentar:

Posting Komentar