C010 A C program to write a function invert(x, p, n) that returns x with the n bits that begin at position p inverted. You can assume that x, p & n are integer variables and that the function will return an integer

By | August 24, 2013

As an example, if x = 181 in decimal which is 10110101 in binary, and p = 4 and n = 2, then the function will return 10101101 or 173 in decimal. The underlined bits are the changed bits. Note that bit positions are counted from the right to the left and that the counts start with a 0 (zero). Therefore, position 4 is the 5th bit from the right values.

Explanation of FUNCTION:

A function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required.

Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by itself. Instead its requests other program like entities – called functions in C – to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind.

The name of the function is unique in a C Program and is Global. It means that a function can be accessed from any location within a C Program. We pass information to the function called arguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing.

We can divide a long C program into small blocks which can perform a certain task. A function is a self contained block of statements that perform a coherent task of same kind.

 

First thing to know before writing this program is conversion of decimal to binary and  conversion of binary to decimal since mainly what is to be done is convert decimal to binary and vice versa and change the inner value and invert the inner digits of binary form of integer.

For more details on conversion of binary to decimal click this link http://www.wikihow.com/Convert-from-Decimal-to-Binary

For more details on conversion of decimal to binary click this link http://www.wikihow.com/Convert-from-Binary-to-Decimal

 

For writing a function and using it in the C program, we should declare the function in the MAIN function. Declaration has to done in the area before the code starts, same area where we declare data variables.

[codesyntax lang=”c”]

int invert(int,int,int);

[/codesyntax]

Function returns value and the ones which does not return any value is called and declared as void. This function which we are writing returns the changed (inverted) value in decimal form as output. The values inside the round brackets are called Arguments. All the Arguments and return type are integer type. A function can return only one value so we have to take only one data type in which its value is expected.

 

Let’s identify variables needed for this program.
First variables will be the one which will save the value entered by the user and it will be X, P and N.  Other variable will be RESULT which will be for holding the resultant values returned by the FUNCTION. The identified variables are X, P, N and RESULT.

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

Main program needs only declaration of variables and function prototype. Also messages for user and scanning values  X, P, N and RESULT is used to display the resultant values returned by the FUNCTION.

[codesyntax lang=”c”]

#include<stdio.h>
void main()
{
     int X,P,N,RESULT;
     int invert(int,int,int);
     clrscr();
     printf("ENTER ANY INTEGER TO INVERT (X) : \n");
     scanf("%d",&X);
     printf("ENTER THE START POSITION TO INVERT (P) :\n");
     scanf("%d",&P);
     printf("ENTER THE LENGTH TO INVERT (N) :\n");
     scanf("%d",&N);
     printf("CONVERTED BINARY VALUE OF %d IS \t",X);
     RESULT=invert(X,P,N);
     printf("\nINVERTED INTEGER IN DECIMAL FORM IS \t%d",RESULT);
     getch();
}

[/codesyntax]

Let’s identify variables needed for function which is part of program outside main function.
Variables which are passed in the function may not be declared again which are X, P and N.  Now the variables Y which will hold the resultant value to be returned by the FUNCTION. Variable BIN[15] will be holding the binary form of the integer entered by the user and should fit inside it sufficiently,  we take an array of integer of length 15 to hold 15 digits of binary number , since there no other data type to hold binary values. Variable LEN is to find the length of the binary digits inside the array. Variable I which will be for FOR Loop. Variable LIMIT will be helping us to check the value of P and N added together should not exceed length of binary form integer. The identified variables are I, Y, LIMIT, LEN and BIN[15].

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

[codesyntax lang=”c”]

int I,Y,LIMIT,LEN,BIN[15];

[/codesyntax]

 

Explaination of WHILE LOOP:

while (condition){}

We can check condition in while loop. Condition will always give you the result to be True or False. LOOP continues till the condition is True and Stops when condition is False. If condition is not going to be false by itself, you need increment or decrement so that the value which is set has to change and make the Condition False sometime to be terminated.

Code for converting decimal to binary

Here initialize length to zero. X is the integer entered by the user it should be a positive integer and for converting decimal to binary the remainder is saved inside array (BIN []) at LEN position which is initially zero and increases till the integer is positive. Now the value of X integer should be saved by the Quotient of the integer divided by two.

[codesyntax lang=”c”]

LEN=0;
     while(X>0)
     {
                BIN[LEN]=X%2;
                X=X/2;
                LEN++;
     };

[/codesyntax]

Code for printing binary form of integer

Since the array formed is in the reverse form of binary equivalent the printing of array values is done in the reverse form. Variable LEN gives us the length and array is always starting with 0 to len-1, hence the first value to print is on position BIN[LEN-1] and last value is on position BIN[0]. To have a reverse movement we need decrement, so we have I—(I minus minus i.e. i=i-1). Now print the value which in an array at position I (i.e. BIN[I]).

[codesyntax lang=”c”]

for(I=LEN-1;I>-1;I--)
     {
                printf("%d ",BIN[I]);
     }

[/codesyntax]

In this program there is a risk of generating an ERROR or exception. Here we have to Check the values given in P and N variables, which should be smaller numbers. P should be less than LEN length (i.e. P<LEN) and N should also be less than LEN length (i.e. N<LEN). Hence if condition checking LIMIT less than LEN. And LIMIT holding addition of P and N (i.e. LIMIT =P+N). and if condition is false printing appropriate message to the user.

[codesyntax lang=”c”]

if(LIMIT < LEN)
{
\\Code to convert
}
else
{
printf("YOU HAVE ENTERED LARGE VALUE FOR P AND N");
}

[/codesyntax]

Code for inverting the binary values from given position P and to the N number of values to be changed.

Variable P gives us the position from where the values are to be inverted and the value of I will be initialized to P-1, since array is always starting with 0 to len-1 and till P+N-1 (i.e. 4th position will be Bin[3]). Now were ever we find ONE replace it by ZERO and vice versa. And save the inverted value in array at position I (i.e. BIN[I]).

for(I=P-1;I<P+N-1;I++)
{
if(BIN[I]==0)
BIN[I]=1;
else
BIN[I]=0;
}

After this print inverted binary value and there is \t used in printf function which is a TAB character the other which we now is \n which is NEW LINE character.

Code for converting binary to decimal

Here FOR loop starts with LEN-1 is zero. Y is the integer to hold new decimal integer after inverting given integer and for converting binary to decimal the remainder is added to Y from array position (BIN [I]) which is initially zero or one and multiplied to TWO. Now the decimal equivalent value of binary inverted  integer saved in Y variable and returned back from where it is called.

[codesyntax lang=”c”]

for(I=LEN-1;I>=0;I--)
     {
            Y=Y*2+BIN[I];
     }
return Y;

[/codesyntax]

Note:- Remember whenever you are calling a function which is returning a value it should always be assigned to a variable of same data type or called inside the printf function as variable.

C program code :

[codesyntax lang=”c” lines=”normal”]

#include<stdio.h>
void main()
{
     int X,P,N,RESULT;
     int invert(int,int,int);
     clrscr();
     printf("ENTER ANY INTEGER TO INVERT (X) : \n");
     scanf("%d",&X);
     printf("ENTER THE START POSITION TO INVERT (P) :\n");
     scanf("%d",&P);
     printf("ENTER THE LENGTH TO INVERT (N) :\n");
     scanf("%d",&N);
     printf("CONVERTED BINARY VALUE OF %d IS \t",X);
     RESULT=invert(X,P,N);
     printf("\nINVERTED INTEGER IN DECIMAL FORM IS \t%d",RESULT);
     getch();
}

int invert(int X,int P,int N)
{
     int I,Y,LIMIT,LEN,BIN[15];
     LEN=0;
     while(X>0)
     {
    BIN[LEN]=X%2;
    X=X/2;
    LEN++;
     };

     for(I=LEN-1;I>-1;I--)
     {
    printf("%d ",BIN[I]);
     }
     printf("\n");
     LIMIT=P+N;
     if(LIMIT < LEN)
     {
    for(I=P-1;I<P+N-1;I++)
    {
        if(BIN[I]==0)
            BIN[I]=1;
        else
            BIN[I]=0;
    }
     }
     else
     {
       printf("YOU HAVE ENTERED LARGE VALUE FOR P AND N");
     }

     printf("INVERTED INTEGER IN BINARY FORM IS \t");
     for(I=LEN-1;I>-1;I--)
     {
      printf("%d ",BIN[I]);
     }
     Y=0;
     for(I=LEN-1;I>=0;I--)
     {
    Y=Y*2+BIN[I];
     }
     return Y;
}

[/codesyntax]

Screen Shots :-

C_program_Invert_Function

C_program_Invert_Function_Output

 

Note:- To understand program for sequence in detail Please SEARCH numerically example: C001, C002, etc.

Leave a Reply