Read the description of sum or difference program

solution-of-sum-or-difference-program-in-c-sum-or-difference
sum-or-difference-program-in-c

Here in this sum or difference program we have to take two integers as input from user. The we have to check if the first number is greater than we have to print their difference. Otherwise we have to print their sum. One thing should take into account that if the two number is equal then it automatically print the sum as the first number is not greater than the second one.

We have taken this problem from CodeChef for practice and learning purpose only of them who want to become a problem solver in future. Here we will discuss the solution this problem using C language. You can use other language too to write the solution to this problem.

You should try to invent other ways to make the solution of this problem. So, let’s see the solution first.

Solution of this sum or difference problem using C

At first we will take two integer from user and store them in two variable a and b. Then we will use if else condition to check if the first number is greater than second number or not.

If the first number is greater than second, then we will subtract second number from first number and print the result. Otherwise we will print the sum of the two numbers.

If a user give two number,

a  =  10;

b  =  8;

result  =  a  –  b  =  (10  –  8)  =  2;

Because a > b here.

Again if he gives two number,

a  =  20;

b  =  25;

then result  =  a  +  b  =  (20  +  25)  =  45;

Because a <= b here.

Now, let’s go to the code bellow to implement this situation.

// solution of sum or difference problem using C

#include <stdio.h>

int main(){
    int a, b;
    
    scanf("%d", &a);
    scanf("%d", &b);
    
    if(a > b){    // check if a > b
        printf("%d\n", a - b);
    }else{
        printf("%d\n", a + b);
    }
    
return 0;
}

Output of this sum or difference program

You will see the following output when you compile and run the above program.

82
28
54

Here, the user gives 82 as the first number and 28 as the second number. As 82 > 28, so the program will print their difference which is in third line 54. But run this program and give input 28 as first number and 82 as second number. The output will be as like as bellow.

28
82
110

However if you give two same number as input, then the program also add them and print the sum of them.

70
70
140

Previous pageFind square root

Next page:  Chef and operators