Sum and Difference of two numbers – Computer Sir Ki Class

Code Learning #JAVA#569

Sum and Difference of two numbers

Gives you understanding of declaration along with dynamic initialization

Learning Objectives

To learn java concepts related to :

• Initializing variables dynamically.

Program Approach

The objective is to demonstrate the dynamic initialization and declaration of variables.

We will be firstly declaring two variables with their initial values. Then we will be initializing a third variable with the sum and the fourth variable with difference of the stored values.

Source Code

 class SumDifference { public static void main(String[] args) { int num1=20; int num2=40; int sum=num1+num2; int dif=num2-num1; System.out.println("The sum of two numbers is "+sum); System.out.println("The difference of two numbers "+dif); } } .linedwrap { border: 1px solid #c0c0c0; padding-top: 5px; padding-bottom: 5px; border-radius: 4px; background-color:#F8F8F8; } .linedtextarea { padding: 0px; margin: 0px; background-color:#F8F8F8; } .linedtextarea textarea, .linedwrap .codelines .lineno { font-size: 12pt; font-family: monospace; line-height: normal !important; } .linedtextarea textarea { padding-right:0.3em; padding-top:0.3em; border: 0; } .linedwrap .lines { margin-top: 0px; width: 20px; float: left; overflow: hidden; border-right: 1px solid #c0c0c0; margin-right: 10px; } .linedwrap .codelines { padding-top: 5px; } .linedwrap .codelines .lineno { color:#AAAAAA; padding-right: 2px; padding-top: 0.0em; text-align: right; white-space: nowrap; } .linedwrap .codelines .lineselect { color: red; }

Run Output

``````The sum of two numbers is 60.
The difference of two numbers is 20.``````

Code Understanding

int sum=num1+num2;

In this line we have initialized the variable sum with the sum of the values stored in the variables num1 and num2.

int dif=num2-num1;

In this line we have initialized the variable dif with the difference of the values stored in the variables num2 and num1.

Suggested Filename(s): SumDifference.java

admin| Created: 16-Aug-2016 | Updated: 21-Mar-2018|

×