News:

Choose a design and let our professionals help you build a successful website   - ITAcumens

Main Menu

Test a number is even or odd by using bitwise operators

Started by thiruvasagamani, Sep 22, 2008, 12:26 PM

Previous topic - Next topic

thiruvasagamani

Test a number is even or odd by using bitwise operators

#include <stdio.h>
#include <coinio.h>
main()
{
int n;
printf(" enter any +ve integer \n");
scanf("%d",&n);
if( n & 1 == 1) // if last bit in numbers is 1, 'n' is odd , 0 for even
printf(" odd number\n");
else
printf(" even number \n");
getch();
}


o/p:
If you enter 'n' value as 25 output is odd number, or if you enter 24 output is even number

Swapping two values by using bitwise operators

#include <stdio.h>
#include <conio.h>
main()
{
int a , b;
printf(" enter any 2 integers \n");
scanf("%d%d", &a , &b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf(" a = %d \n", a);
printf( " b = %d \n", b);
getch();
}

o/p:
If you enter a, b values as 5, 6 output is a = 6 , b = 5
Thiruvasakamani Karnan