Program to find parity in C++


In this tutorial, we will be discussing a program to find parity.

For this we will be provided with a number. Our task is to find its parity i.e count of whether the number of ones are odd or even.

Example

 Live Demo

# include<bits/stdc++.h>
# define bool int
using namespace std;
//finding the parity of given number
bool getParity(unsigned int n) {
   bool parity = 0;
   while (n){
      parity = !parity;
      n = n & (n - 1);
   }
   return parity;
}
int main() {
   unsigned int n = 7;
   cout<<"Parity of no "<<n<<": "<<(getParity(n)? "Odd": "even");
   getchar();
   return 0;
}

Output

Parity of no 7: odd

Updated on: 19-May-2020

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements