Tuesday, November 25, 2014

C using bitwise pro



C Program to Convert a Decimal Number to Binary & Count the Number of 1s

#include 
    #include
void main()
{
long num, decimal_num, remainder, base = 1, binary = 0, no_of_1s = 0;
   clrscr();
printf("Enter a decimal integer \n");
scanf("%ld", &num);
decimal_num = num;
while (num > 0)
{
remainder = num % 2;
if (remainder == 1)
{
no_of_1s++;
}
binary = binary + remainder * base;
num = num / 2;
base = base * 10;
}
printf("Input number is = %d\n", decimal_num);
printf("Its binary equivalent is = %ld\n", binary);
printf("No.of 1's in the binary number is = %d\n", no_of_1s);
getch();
}
 
Output
 
Enter a decimal integer
134
Input number is = 134
Its binary equivalent is = 10000110
No.of 1's in the binary number is = 3

C Program to find if a given Year is a Leap Year

#include
#include
void main()
{
    int year;
    clrscr();
    printf("Enter a year \n");
    scanf("%d", &year);
    if ((year % 400) == 0)
        printf("%d is a leap year \n", year);
    else if ((year % 100) == 0)
        printf("%d is a not leap year \n", year);
    else if ((year % 4) == 0)
        printf("%d is a leap year \n", year);
    else
        printf("%d is not a leap year \n", year);
    getch();
}
 
Output
 
Enter a year
2012
2012 is a leap year

C Program to Swap the Contents of two Numbers using Bitwise XOR Operation

 
#include 
    #include
void main()
{
long i, k;
clrscr();
printf("Enter two integers \n");
scanf("%ld %ld", &i, &k);
printf("\n Before swapping i= %ld and k = %ld", i, k);
i = i ^ k;
k = i ^ k;
i = i ^ k;
printf("\n After swapping i= %ld and k = %ld", i, k);
getch();
}
 
Output

Enter two integers
45
89
Before swapping i= 45 and k = 89
After swapping i= 89 and k = 45

C Program to Convert a Given Number of Days in terms of Years, Weeks & Days

#include 
#include
#define Daysinweek 7
void main()
{
    int ndays, year, week, days;
    printf("Enter the number of daysn");
    scanf("%d", &ndays);
    year = ndays / 365;
    week =(ndays % 365) / Daysinweek;
    days =(ndays % 365) % Daysinweek;
    printf ("%d is equivalent to %d years, %d weeks and %d daysn",
            ndays, year, week, days);
    getch();
}
 
Output

Enter the number of days
29
29 is equivalent to 0 years, 4 weeks and 1 days

No comments:

Post a Comment