Write a program that reads two integer values (A and B) from the keyboard and displays the sign of the sum of A and B without performing the addition.
Use the fabs function from the <math.h> library.
Difficulty level
Video recording
This exercise is mostly suitable for students
#include<stdio.h>
#include <math.h>
int main()
{
int A, B;
printf("Enter 2 integers :");
scanf("%i %i", &A, &B);
if ((A>0 && B>0) || (A<0 && B>0 && fabs(A)<fabs(B))
|| (A>0 && B<0 && fabs(A)>fabs(B)))
printf("The sign of the sum %i + %i is positive\n",A,B);
else if ((A<0 && B<0) || (A<0 && B>0 && fabs(A)>fabs(B))
|| (A>0 && B<0 && fabs(A)<fabs(B)))
printf("The sign of the sum %i + %i is negative\n",A,B);
else
printf("The sum %i + %i is zero\n", A, B);
return 0;
}
The above solution doesn't work correctly when one of the integers is 0.
Corrected version provided by Hadi Mazloum
#include<stdio.h>
#include <math.h>
int main()
{
int A, B;
printf("Enter 2 integers :");
scanf("%i %i", &A, &B);
if ((A>0 && B>0) || (A<=0 && B>0 && fabs(A)<fabs(B))
|| (A>0 && B<=0 && fabs(A)>fabs(B)))
printf("The sign of the sum %i + %i is positive\n",A,B);
else if ((A<0 && B<0) || (A<0 && B>=0 && fabs(A)>fabs(B))
|| (A>=0 && B<0 && fabs(A)<fabs(B)))
printf("The sign of the sum %i + %i is negative\n",A,B);
else
printf("The sum %i + %i is zero\n", A, B);
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Asymptotic Analysis 20