Spread the love

Write a C program to increment number without using + sign

 

#include <stdio.h>

int Increment(unsigned int i)
{
	unsigned int mask = 1;
	while (i & mask)		// Step 1
	{
		i = i & (~mask);	// Step 2
		mask = (mask<<1);	// Step 3
	}
	i = i | mask;			// Step 4
	
	return i;
}

int main( )
{
	printf("%d", Increment(1));
	
	return 0;
}

 

Explanation with example – Let we take example of number 1, so output would be 2 as we know, but we would go through each step separately so that logic become more clear.

Step 1: – Binary of ‘1’ is 0001 which will AND(&) with mask and result would be 1.

Step 2: – this step is simplified like this,

               i = i & (~mask);            // Step 2

               i = (0001) & (~0001);    

               i = (0001) & (1110);   

               i = 0

Step 3: – mast now shifted left, so it become 2,

Step 4: – Now value of i = 0, mask = 2

               So,    i = i | mask;            // Step 4

               i = 0000 | 00010;

               i = 2 , and here is output

Output

Write a C program to increment number without using + sign

 

Suggested Reading

  1. Add two numbers without using arithmetic operators
  2. Smallest of three integers without comparison operators
  3. Find middle number out of three numbers