This blog is under construction

Sunday, 14 July 2013

C program to toggle nth bit

Write a C program to toggle nth bit.

  #include <stdio.h>

  int main() {
        int value, n, result;

        /* get the input value from the user */
        printf("Enter your input value:");
        scanf("%d", &value);

        /* get the location of the bit to be toggled */
        printf("Enter the bit to be toggled:");
        scanf("%d", &n);

        /* toggle nth bit */
        result = value ^ (1 << n);

        /* print the result */
        printf("Result : %d\n", result);
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:3
  Enter the bit to be toggled:1
  Result : 1


  1. This comment has been removed by the author.

  2. Write a C program to add all "special cube numbers" between 2 intervals of numbers specified.

    Constraints :
    A positive integer is called a "Special cube number" if the sum of cubes of individual digit is equal to that number itself. For example:
    153 =1*1*1+ 5*5*5 + 3*3*3 //153 is a "special cube number".
    12 is not equal to 1*1*1+2*2*2 // 12 is not a "special cube number".

    Sample Input:

    Sample Output:

  3. Hi, Your code is not correct :
    13th line in your code should be -
    result = value ^ (1 << (n-1));

    According to your code toggle one next it than actual input...