29. Program that could find whether the number entered is odd or even and whether it is prime or not. Before termination find the total number of odds, evens and primes entered.

Chapter 6: 

Looping Structures

Programming Exercise

Problem # 29:

Write a program that could find whether the number entered through keyboard is odd or even and should also tell that whether it is prime or not. The program should keep on taking the value till the user ends and before termination should find the total number of odds, evens and primes entered.

Solution:

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    int c, n, p, prime=0, o_num=0, e_num=0;
    cout<<"Enter a number and press 0 to stop taking values: ";
    cin>>n;
    while(n!=0)
    {  
    if(n%2==0)
    {
        cout<<n<<" is an even number."<<endl;
        e_num++;
    }
    else
    {
        cout<<n<<" is an odd number."<<endl;
        o_num++;
    }
  
    p=1;
    for(c=2;c<n;c++)
    {
    if(n%c==0)
    {
        p=0;
        break;
    }
    }
    if(p==1&&n!=1)
    {
    cout<<endl<<n<<" is a prime number."<<endl;
    prime++;
    }
  
    cout<<"\nEnter a number and press 0 to stop taking values: ";
    cin>>n;
    }
    cout<<"\ntotal even numbers entered are:"<<e_num;
    cout<<"\ntotal odd numbers entered are:"<<o_num;
    cout<<"\ntotal prime numbers entered are:"<<prime;
    getch();
}

Let me know in the comment section if you have any question.

Previous Post:
28. Program to calculate the sum of the first n odd integers.

Comments