Given two Integers A and B, your task is to find the sum and difference of two numbers.
Examples:
Input: A = 4, B = 9
Output: Sum = 13 and Difference = -5
Input: A = -3, B = -2
Output: Sum = -5 and Difference = -1
Approach:
The problem can be solved using arithmetic operators.
Operations on Numbers:
- Addition (+): This operation is used to add the inputs to get the output. For example, when 2 is added to 3 the resultant will be equal to the sum of both the numbers which is equal to 5, (2 + 3 = 5).
- Subtraction (-): This operation is used to subtract the inputs to get the result. For example, when 3 is subtracted by 2 the resultant will be equal to the difference of both the numbers which is equal to 1 (3 – 2 = 1).
Step-by-step algorithm:
- Read A and B from the user
- Calculate the sum: result = A + B
- Calculate the difference: result = A – B
- Display the results.
Below is the implementation of the above approach:
C++
#include <iostream> using namespace std;
int main()
{ int A, B;
A = 4;
B = 9;
cout << "Sum of " << A << " and " << B << " = " << A + B
<< endl;
cout << "Difference of " << A << " and " << B << " = "
<< A - B << endl;
} |
Java
public class MainClass {
public static void main(String[] args) {
// Declaring and initializing variables A and B
int A, B;
A = 4 ;
B = 9 ;
// Printing the sum of A and B
System.out.println( "Sum of " + A + " and " + B + " = " + (A + B));
// Printing the difference of A and B
System.out.println( "Difference of " + A + " and " + B + " = " + (A - B));
}
} |
Python3
# Python code A = 4
B = 9
# Printing the sum of A and B print (f "Sum of {A} and {B} = {A + B}" )
# Printing the difference of A and B print (f "Difference of {A} and {B} = {A - B}" )
|
C#
using System;
class MainClass
{ public static void Main( string [] args)
{
int A, B;
A = 4;
B = 9;
// Printing the sum of A and B
Console.WriteLine($ "Sum of {A} and {B} = {A + B}" );
// Printing the difference of A and B
Console.WriteLine($ "Difference of {A} and {B} = {A - B}" );
}
} |
Javascript
let A, B; A = 4; B = 9; console.log( "Sum of " + A + " and " + B + " = " + (A + B));
console.log( "Difference of " + A + " and " + B + " = " + (A - B));
|
Output
Sum of 4 and 9 = 13 Difference of 4 and 9 = -5
Time Complexity: O(1)
Auxiliary Space: O(1)
Article Tags :
Recommended Articles