Header Ads

10 - WAP to Increment (Pre/Post) a Number without using Increment operator (++) in C.

This program Pre-Increment's & Post-Increment, a Number without using Increment operator (++) in C.
  • The Number are used and are Incremented before and after passing to a Expression, in order to get the "Pre & Post Increment" value before and after performing incrementing operation.
//program to increment a number without using increment operator
#include 
//increment function
int increment(int *num)
{
      //declaring local variables
      int idx = 1, flag;
      static int value;
      value = *num;
      do
      {
       //to set the bit which is low
       *num = idx ^ *num;
       //checking that the bit is set or noy
       flag = idx & *num;
       //if bit was set check the next bit
       if (flag == 0)
       {
        idx = idx << 1;
        }
      }while (flag == 0);
 return value;
}

//main function
int main()
{
     //declaration of variables
            int num, result;
            char choice;
     //asking user toenter a number
     printf ("Enter a Number : ");
     scanf ("%d", &num);
          getchar();
     //calling the increment function
     result = increment(&num);
     //printing the value after increment and before increment
     printf ("Pre Increment Value is : Before = %d, After = %d\n", num, num);
     printf ("Post Increment Value is : Before = %d, After = %d\n", result, num);
        return 0;
}

Program Output:

 

No comments