Prime and composite numbers
Prime numbers are those numbers which are divisible by 1 and itself only. A prime number doesn't have any pattern but can be determined by the division process.
E.g. 2,3,5,7,...etc. (i.e. 7 is divisible by 1 and itself only, so it is a prime number.)
E.g. 2,3,5,7,...etc. (i.e. 7 is divisible by 1 and itself only, so it is a prime number.)
Composite numbers are those numbers which are not prime numbers. Those numbers which are divisible by any numbers other than 1 and itself are called composite numbers.
E.g. 4,6,9...etc.(i.e. 4 is divisible by 1,2 and 4, so it is a composite number.)
Zero and one (0,1) are neither prime nor composite numbers.
E.g. 4,6,9...etc.(i.e. 4 is divisible by 1,2 and 4, so it is a composite number.)
Zero and one (0,1) are neither prime nor composite numbers.
Write a program in C++ to check whether the given number is prime, composite or none.
Firstly the number entered by the user is stored in the integer type variable. A for loop is executed from 1 to the input number. A counter is set and increases if any number within the loop divides it. Finally, the prime numbers will have two(2) as their counter value. Composite numbers will have a number greater than two(2) as their counter value. For zero the for loop won't be executed and the statement in if condition will be executed.
Program
#include<iostream.h>
#include<conio.h>
void main()
{
int num,i,b=0;
clrscr();
cout<<"Enter a number=";
cin>>num;
for(i=1;i<=num;i++)
{
if ((num%i)==0)
b++;
}
if ( num==0)
if ( num==0)
cout<<"\nThe number is neither prime nor composite";
else if(b==2)
cout<<"\nThe number is prime";
else if(b>2)
cout<<"\nThe number is composite";
else
cout<<"\nInvalid input";
else
cout<<"\nInvalid input";
getch();
}
Explanation
In the above program, we entered a number 7 and it was stored in num. Then the for loop was executed from 1 to 7, 7 was divided by all numbers within the loop. It was divisible by only two number (1 and 7), so the value of counter b increased twice (i.e. b=2). This condition is true for prime numbers, so 7 is a prime number.
Fact about C++
In C++ we can use endl instead of \n. [endl=end of line]
Syntax: cout<<"Thank"<<endl<<"You";
Thank will be printed and You will be printed in the next line.
Output screen
Thank
You
Output screen
Thank
You
No comments:
Post a Comment