Q:

C Example to subtract two integers without using Minus (-) operator

0

C Example to subtract two integers without using Minus (-) operator

In this program, we will study how we can print subtraction between two integer values without using minus (-) operator? We will use bitwise complement for getting the same.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include<stdio.h>

int main()
{
	int a,b,sub;
	
	//input numbers
	printf("Enter first number: ");
	scanf("%d",&a);
	printf("Enter second number: ");
	scanf("%d",&b);
	
	//find subtraction using ~
	sub=a+~b+1;
	
	printf("subtraction of %d-%d=%d",a,b,sub);
	
	return 0;
}

Output

Enter first number: 10
Enter second number: 2
subtraction of 10-2=8

Here, sum = a+~b+1 i.e. variable a has its normal value, but the value of variable b is complemented i.e. '2' becomes '-3'.

a+~b+1= 10+(-3)+1=10-3+1=8.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C programming Basic Input, Output, if else, Ternary Operator based Programs

Similar questions


need a help?


find thousands of online teachers now
C Example for different floating point values pred... >>
<< C program to generate random numbers within a rang...