In: Computer Science
THIS PROGRAM HAS TO BE WRITTEN IN C
Single function to perform the parity computation on the input integer passed to this function. The output of the function is 0 if the input has even parity (that is, the number of 1s in the binary representation of the input is even) and 1 if the input has odd parity (that is, the number of 1s in the binary representation of the input is odd).
CODE:
#include <stdio.h>
//Function to compute parity
int parity_compute(int a){
//To store the count of 1 in binary representation of a
int count=0;
//iterate until a becomes 0
while(a!=0){
//if last bit is 1
if(a&1==1){
//increment count by 1
count++;
}
//Right Shift to delete last bit from the binary representation of
number
a = a>>1;
}
//If no of 1s is even, it will return 0
if(count%2==0){
return 0;
}
//If no of 1s is odd, it will return 1
return 1;
}
int main()
{
//To store the input
int a;
printf("Enter a number : ");
//To take the input from the user
scanf("%d",&a);
//calling the parity_compute() and printing returned value
printf("%d",parity_compute(a));
return 0;
}
OUTPUT: