Home » C solved programs » C basic programs

C program to find the difference of two numbers

This program will find the difference of two integer numbers. Difference is quite different from subtraction, in subtraction we just subtract second number from first number and here to get difference we will subtract smallest number from largest number, so that we can get correct difference of them.

Difference of two integer numbers program



/*C program to find difference of two numbers.*/
 
#include <stdio.h>
 
int main()
{
     
    int a,b;
    int diff;
 
    printf("Enter first number: ");
    scanf("%d",&a);
    printf("Enter second number: ");
    scanf("%d",&b);
 
    // check condition to identify which is largest number
    if( a>b )
        diff=a-b;
    else
        diff=b-a;
 
    printf("\nDifference between %d and %d is = %d",a,b,diff);
    return 0;
}

Output

First Run:
Enter first number: 120
Enter second number: 30

Difference between 120 and 30 is = 90

Second Run:
Enter first number: 30
Enter second number: 120

Difference between 30 and 120 is = 90

Using abs() – A Shortest way to find difference of two numbers

By using abs() function we can get the difference of two integer numbers without comparing them, abs() is a library function which is declared in stdlib.hThis function returns the absolute value of given integer.

Consider the example



/*C program to find difference of two numbers using abs().*/
 
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
     
    int a,b;
    int diff;
 
    printf("Enter first number: ");
    scanf("%d",&a);
    printf("Enter second number: ");
    scanf("%d",&b);
 
    diff=abs(a-b);
 
    printf("\nDifference between %d and %d is = %d",a,b,diff);
    return 0;
}

Output

First Run:
Enter first number: 120
Enter second number: 30

Difference between 120 and 30 is = 90

Second Run:
Enter first number: 30
Enter second number: 120

Difference between 30 and 120 is = 90





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.