Implement a function threefourths which takes one value as argument and do the computation of 3*x/4 using bit level coding rules and thus not cause overflow.

Program Plan:

·        Define the function threefourths which takes integer values as an argument.
·        Perform the computation using bit level coding rules.
·        Declare and initialize a testing_data to check whether mul3div4 so the same result as testing_data array.
·        Define the main method from where the execution of program begins.
·        Iterate for loop till value of i is less than the size of one element of array.
·        Display value of 3*x/4 using printf statement.
·        Display value of 3*x/4 by calling threefourths.


Program:

/*********************************************************** Implement a function threefourths which takes one value* * as argument and do the computation of 3*x/4 using bit  * * level coding rules and thus not cause overflow.        *                                    
**********************************************************/

// Include header files.
#include<stdio.h>
#include<limits.h>

Define the function mul3div4 which takes integer values as an argument.

int threefourths(int x)
{
    // calculate 3x to y.
    int y=x+x+x;
    // perform computation using bit level coding rules.
    return(y >= 0) ? (y >> 2) : -(int)((UINT_MAX - y + 1)
                                         >> 2);
}

Declare and initialize an array.

int testing_data[]=
{
    0,1,-1,-9,INT_MIN, INT_MAX
};

Define the main method from where the execution of program begins.

int main()
{
    // declare an integer variable.
    int i;
    // Iterate for loop till value of i is less than the
    // size of one element of array.
    for(i=0;i<sizeof(testing_data)/
           sizeof(testing_data[0]);i++)
    {
        // display value of 3*x/4 using printf statement.
        printf("3*%d/4=%d\n",testing_data[i],
                              testing_data[i]*3/4);
        // display value of 3*x/4 by calling threefourths.
        printf("threefourths(%d) = %d\n", testing_data[i],
                                
        threefourths(testing_data[i]));
        printf("\n");
        printf("\n");
    }
    return 0;
}


Sample Output:

3*0/4=0
threefourths(0) = 0


3*1/4=0
threefourths(1) = 0


3*-1/4=0
threefourths(-1) = 0


3*-9/4=-6
threefourths(-9) = -6


3*-2147483648/4=-536870912
threefourths(-2147483648) = -536870912


3*2147483647/4=536870911
threefourths(2147483647) = 536870911

--------------------------------
Process exited with return value 0

Press any key to continue . . .

Post a Comment

Previous Post Next Post